How do I output to textField? - java

I'm making a java program to turn any text into capital capital letters.
It worked fine with system.out.print but now I want to turn it into a GUI.
I tried getting the text from the original textField input, turn it into a double, turn the double into a string then I used addText but I don;t think it works.
Here is how it is supposed to work:
I write a bunch a text into a the input box then when I click the GO button it converts every character into capital letters. The output is supposed to to inside another TextField
here is my code (using Eclipse)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame1 {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Frame1() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 710, 508);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblInputTextTo = new JLabel("Input Text to Capitalise:");
lblInputTextTo.setFont(new Font("Segoe UI", Font.BOLD, 26));
lblInputTextTo.setBounds(210, 0, 289, 54);
frame.getContentPane().add(lblInputTextTo);
textField = new JTextField();
textField.setBounds(34, 77, 624, 150);
frame.getContentPane().add(textField);
textField.setColumns(10);
textField_1 = new JTextField();
textField_1.setBounds(34, 354, 613, 90);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
JButton btnGo = new JButton("GO!");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double TextInput = Double.parseDouble(textField.getText());
String Str = String.valueOf(TextInput);
textField_1.setText(Str.toUpperCase());
textField_1.setEditable(false);
}
});
btnGo.setFont(new Font("Segoe UI", Font.BOLD, 18));
btnGo.setBounds(250, 239, 180, 23);
frame.getContentPane().add(btnGo);
JLabel lblOutput = new JLabel("Output:");
lblOutput.setFont(new Font("Segoe UI", Font.BOLD, 26));
lblOutput.setBounds(304, 300, 95, 43);
frame.getContentPane().add(lblOutput);
}}
I'm not done yet if you have some suggestion it would be nice.

You don't need to convert the input String into double to make it uppercase. I did below change to your program and it works now.
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Remove these 2 lines
//double TextInput = Double.parseDouble(textField.getText());
//String Str = String.valueOf(TextInput);
//Directly take input text, make it uppercase and set it in output field.
textField_1.setText(textField.getText().toUpperCase());
textField_1.setEditable(false);
}
});
Additional tip:
Don't do setLayout(null) and use setBounds() to set components in absolute positions. Instead use layout managers. See https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

Related

How to create a lock with user input on JPanel?

I am a beginner at Java so if there are some simple problems that are in my code please tell me. Thank you in advance!
In Java I have a "login" JPanel which I want the user to enter in a password they like, then have them enter the password on another JPanel (the same password that they created). If it is right and they click the login button again then it would bring them to a screen which says "Welcome" and if they don't, then a screen that says "False. Error". However something on Eclipse is saying that something is wrong and that I can't run it. Please tell me where I went wrong and if you can tell me how to fix it. I would appreciate it!
There are two problems with my code. Both of them are "Syntax error, insert "}" to complete ClassBody" but every time I add one in, it says "Syntax error on token "}", delete this token"
Here is my code:
package Button;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.util.Scanner;
#SuppressWarnings("unused")
public class Login {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Pasword");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JButton loginButton = new JButton("Create");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
#SuppressWarnings("resource")
Scanner user = new Scanner (System.in);
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
loginButton.setVisible(false);
registerButton.setVisible(false);
userText.setVisible(false);
userLabel.setVisible(false);
JTextField userText1 = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText1);
JButton loginButton1 = new JButton("Password");
loginButton1.setBounds(10, 80, 80, 25);
panel.add(loginButton1);
});
loginButton1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
String name = userText.getText();
String accept = name;
String good;
if (accept.equals(name)) {
good = "Welcome";
} else {
good = "False. Error";
}
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
label1.setVisible(true);
panel.add(label1);
}
});
}
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
);
Is missing a closing embrace (}) - one thing you will learn to do is count brackets and braces
It should look more like
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//...
}
});
registerButton and loginButton1 are undefined and you seem to be missing closing brace (}) at the end of the file as well
I would also highly recommend that you make use of layout managers, they will make life a lot easier for you. I'd recommend starting with How to use CardLayout as it will allow you to switch between multiple views simply
Thank you for helping me fix the problem. In the end I was able to fix it and it now works. Here it is:
package Button;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.util.Scanner;
#SuppressWarnings("unused")
public class AddOnButton {
public static void main(String[] args) {
JFrame frame = new JFrame("Login Page");
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel userLabel = new JLabel("Password");
userLabel.setBounds(10, 10, 80, 25);
panel.add(userLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100, 10, 160, 25);
panel.add(userText);
JButton loginButton = new JButton("Create");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
String name = userText.getText();
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loginButton.setVisible(false);
userText.setVisible(false);
userLabel.setVisible(false);
JTextField userText1 = new JTextField(20);
userText1.setBounds(100, 10, 160, 25);
panel.add(userText1);
JLabel userLabel1 = new JLabel("Password");
userLabel1.setBounds(10, 10, 80, 25);
panel.add(userLabel1);
JButton loginButton1 = new JButton("Enter");
loginButton1.setBounds(10, 80, 80, 25);
panel.add(loginButton1);
String check = userText1.getText();
loginButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userText1.setVisible(false);
userLabel1.setVisible(false);
loginButton1.setVisible(false);
String good;
if (name.equals(check)) {
good = "Welcome";
} else {
good = "False. Error";
}
JLabel label1 = new JLabel(good);
label1.setBounds(100, 40, 100, 100);
label1.setVisible(true);
panel.add(label1);
}
});
}
});
}
}

How to open new window after JProgressBar is completed

I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}

Passing info from one Jframe to another

I have my original text field in my first frame and I need it to be displayed in my other jframe. The code is:
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
'nameL' is the textbox the user enters their name in.
This code describe where it should be displayed:
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
this is my first class where the user inputs their name
public order(String para){
getComponents();
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;
public class frame1 {
public JFrame frame;
public JTextField nameL;
public JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame1 window = new frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public frame1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setEnabled(false);
frame.setResizable(false);
frame.getContentPane().setBackground(Color.GRAY);
frame.setForeground(Color.WHITE);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JButton btnContinue = new JButton("Continue");
btnContinue.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String msg = nameL.getText();
frame2 fram = new frame2 ();
fram.setVisible(true);
frame.dispose();
new order (msg) .setVisible(true);
}
}
);
btnContinue.setBounds(0, 249, 450, 29);
frame.getContentPane().add(btnContinue);
JTextArea txtrPleaseEnterYour = new JTextArea();
txtrPleaseEnterYour.setEditable(false);
txtrPleaseEnterYour.setBackground(Color.LIGHT_GRAY);
txtrPleaseEnterYour.setBounds(0, 0, 450, 32);
txtrPleaseEnterYour.setText("\tPlease enter your name and email below\n If you do not have or want to provide an email, Leave the space blank");
frame.getContentPane().add(txtrPleaseEnterYour);
JTextArea txtrEnterYourFull = new JTextArea();
txtrEnterYourFull.setEditable(false);
txtrEnterYourFull.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtrEnterYourFull.setBackground(Color.GRAY);
txtrEnterYourFull.setText("Enter your full name");
txtrEnterYourFull.setBounds(52, 58, 166, 29);
frame.getContentPane().add(txtrEnterYourFull);
nameL = new JTextField();
nameL.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
}
);
nameL.setBackground(Color.LIGHT_GRAY);
nameL.setBounds(52, 93, 284, 26);
frame.getContentPane().add(nameL);
nameL.setColumns(10);
JTextArea txtroptionalEnterYour = new JTextArea();
txtroptionalEnterYour.setEditable(false);
txtroptionalEnterYour.setFont(new Font("Lucida Grande", Font.PLAIN, 15));
txtroptionalEnterYour.setBackground(Color.GRAY);
txtroptionalEnterYour.setText("(Optional) Enter your email");
txtroptionalEnterYour.setBounds(52, 139, 193, 29);
frame.getContentPane().add(txtroptionalEnterYour);
textField_1 = new JTextField();
textField_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
textField_1.setBackground(Color.LIGHT_GRAY);
textField_1.setBounds(52, 180, 284, 26);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
}
}
my second class where the text field has to be set
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class order extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
public JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
order frame = new order();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public order() {
setAlwaysOnTop(false);
setTitle("Order Details // Finalization");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 451, 523);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("Submit Order");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setAlwaysOnTop(true);
JOptionPane.showMessageDialog(null, "Your Order Has Been Confirmed", "enjoy your meal", JOptionPane.YES_NO_OPTION);
}
});
btnNewButton.setBounds(164, 466, 117, 29);
contentPane.add(btnNewButton);
}
public order(String para){
getComponents();
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setBounds(91, 27, 254, 84);
contentPane.add(lblNewLabel_1);
lblNewLabel_1.setText(para);
}
}
Open both JFrames, have them listen to the EventQueue for a custom "string display" event.
Wrap the string to be displayed in a custom event.
Throw that on the event queue, allowing both the JFrames to receive the event, which they will then display accordingly.
---- Edited with an update ----
Ok, so you're a bit new to Swing, but hopefully not too new to Java. You'll need to understand sub-classing and the "Listener" design pattern.
Events are things that Components listen for. They ask the dispatcher (the Swing dispatcher is fed by the EventQueue) to "tell them about events" and the dispatcher then sends the desired events to them.
Before you get too deep in solving your problem, it sounds like you need to get some familiarity with Swing and its event dispatch, so read up on it here.

How do I remove a component from a JPanel? and then redisplay the frame?

Some context for this code,
what I am trying to do is create a validation warning if the input containts "" as a value,
so if an error is displayed it displays the message.
If it is valid it does not display a message,
so how do I remove the message when the textField is valid?
The message is a JPanel that contains a JLabel with the text in it,
I add this this JPanel to the frame when it is not valid,
and I am trying to remove it when it is valid.
So what am I doing wrong here?
I am at a basic level with Swing.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 401, 232);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 330, 94);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Firstname :");
lblNewLabel.setBounds(10, 11, 104, 14);
panel.add(lblNewLabel);
textField = new JTextField();
textField.setBounds(76, 8, 244, 20);
panel.add(textField);
textField.setColumns(10);
JLabel lblLastname = new JLabel("Lastname :");
lblLastname.setBounds(10, 42, 78, 14);
panel.add(lblLastname);
textField_1 = new JTextField();
textField_1.setBounds(76, 39, 244, 20);
panel.add(textField_1);
textField_1.setColumns(10);
JButton btnValidate = new JButton("Validate");
btnValidate.addMouseListener(new MouseAdapter() {
#SuppressWarnings("deprecation")
#Override
public void mousePressed(MouseEvent arg0) {
JPanel panel_1 = new JPanel();
JPanel panel_2 = new JPanel();
if(textField.getText().equals("")) {
panel_1.setBackground(new Color(30, 144, 255));
panel_1.setBounds(100, 116, 330, 26);
JLabel lblMessage = new JLabel("0 :");
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_1.add(lblMessage);
frame.getContentPane().add(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
else if(textField_1.getText().equals("")) {
panel_2.setBackground(new Color(50, 200, 255));
panel_2.setBounds(10, 134, 330, 26);
JLabel lblMessage = new JLabel("1 :");
lblMessage.setBounds(50, 50, 50, 50);
lblMessage.setAlignmentX(50);
lblMessage.setForeground(new Color(255, 255, 255));
lblMessage.setFont(new Font("Tahoma", Font.BOLD, 13));
panel_2.add(lblMessage);
frame.getContentPane().add(panel_2);
frame.remove(panel_1);
frame.revalidate();
frame.repaint(10);
frame.revalidate();
}
}
});
btnValidate.setBounds(231, 71, 89, 23);
panel.add(btnValidate);
}
}
The easiest way is to simply adjust the visibility (JComponent#setVisible( false ) ).
If you really want to remove the component completely, you have to remove and revalidate, as documented in the Container#remove method
This method changes layout-related information, and therefore, invalidates the component hierarchy. If the container has already been displayed, the hierarchy must be validated thereafter in order to reflect the changes.
which results in code like
panel.remove( componentToRemove );
panel.revalidate();
panel.repaint();
As a side note: please replace the null layout and those setBounds call by a proper LayoutManager. You might want to take a look excellent 'Nested layout example' available on SO to see what is possible with layout managers. The Swing tag info on SO contains some extra useful links when starting to work with layout managers
yourpanel.setVisible(false); should hide your panel, where "yourPanel" is your JPanel instance

Problem in passing value of JTable cell of one JFrame form to another form's JTextField

I have two JFrame Forms-SelectContactsfrm.java and Taskfrm.java. There is JTable in SelectContactsfrm file to show the contacts.When user select a contact from JTable and when he/she press OK button,selected values should be copied into Taskfrm.java's JTextField.
Taskfrm.java's JTextField's name is-txtContacts and access modifier is-public
Below is the code which I wrote on SelectContactsfrm's OK button's actionPerformed.Button name-btnOK
private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {
// Code to get the selected rows value and paste Contact's full name in Taskfrm's txtContacts JTextField:
selrow=ctable.getSelectedRow();
selcol=ctable.getSelectedColumn();
Object value=ctable.getModel().getValueAt(selrow,1);
new Taskfrm().txtContacts.setText(value.toString());
//Just to check whether I get the correct values or not.
System.out.println("selrow=="+selrow);
System.out.println("selcol=="+selcol);
System.out.println("txtContacts=="+value);
}
I can see the correct selected values in output but didnt get why this value has not been set in Taskfrm's JTextField.In Taskfrm's constructor only initComponents() is there.Is there any way to attach class files here instead of pasting?
It depends on how Taskfrm is set up and what is in it's constructor.
I tried something like this and it works
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ClassA extends JFrame {
JTextField text;
public ClassA() {
JLabel l = new JLabel("Name: ");
text = new JTextField(20);
JButton b = new JButton("Send");
setLayout(null);
l.setBounds(10, 10, 100, 20);
text.setBounds(120, 10, 150, 20);
b.setBounds(120, 40, 80, 20);
add(l);
add(text);
add(b);
setVisible(true);
setSize(300, 100);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ClassB().text.setText(ClassA.this.text.getText());
}
});
}
public static void main(String a[]) {
new ClassA();
}
}
class ClassB extends JFrame {
JTextField text;
public ClassB() {
JLabel l = new JLabel("Name: ");
text = new JTextField(20);
setLayout(null);
l.setBounds(10, 10, 100, 20);
text.setBounds(120, 10, 150, 20);
add(l);
add(text);
setVisible(true);
setSize(300, 100);
}
}
set its visibility and made changes in Taskfrm's constructor.Now its working.
new Taskfrm(value);
new Taskfrm(value).setVisible(true);

Categories

Resources