This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am just a beginner in Java. Here, I want to make a User ID & Password input, which will get checked & tell its Right or wrong. But each time it's giving the wrong answer despite inputting the correct combination.
Here is my code:
import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Zihan {
public JFrame frame;
public JTextField textField;
public JPasswordField passwordField;
public static String gtxt,ptxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Zihan window = new Zihan();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Zihan() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblEmailuserId = new JLabel("Email/User ID:");
lblEmailuserId.setBounds(76, 30, 90, 14);
frame.getContentPane().add(lblEmailuserId);
textField = new JTextField();
textField.setBounds(171, 27, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(171, 87, 86, 20);
frame.getContentPane().add(passwordField);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(76, 90, 69, 14);
frame.getContentPane().add(lblPassword);
JButton btnLogIn = new JButton("Log In");
btnLogIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
gtxt = textField.getText();
ptxt = passwordField.getText();
new CheckID(gtxt,ptxt);
JFrame login = new JFrame("Login window");
login.setSize(200, 200);
login.setVisible(true);
JLabel msg = new JLabel();
msg.setText(CheckID.msgt);
login.getContentPane().add(msg);
frame.setVisible(false);
}
});
btnLogIn.setBounds(121, 137, 89, 23);
frame.getContentPane().add(btnLogIn);
}
}
& This is the CheckID class to check Email & Password:
public class CheckID {
public static String msgt;
String cU = "zihan";
String cP = "123";
CheckID(String tx ,String px){
if(tx==cU && px ==cP)
{
msgt = "Welcome to messenger";
}
else
{
msgt = "Sorry! Wrong Password/Email";
}
}
}
Change
if(tx==cU && px ==cP)
to
if(tx.equals(cU) && px.equals(cP))
Related
I have two JFrame windows one for the login and the second for the welcome. Now I want to present the Firstname and the Lastname of the connected user near to the hello in the welcome screen.
I tried many things but none of them worked so I'm asking for you help. I just started to learn GUI:
The login code:
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frame;
private JLabel MainLogo;
String Firstname=null;
String Lastname=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connected = null;
private JTextField UsernameFiled;
private JPasswordField passwordField;
public Login() {
initialize();
connected = DBConnection.DBconnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 560, 256);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("UserName: ");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(160, 11, 140, 50);
frame.getContentPane().add(lblNewLabel);
JLabel lblPassword = new JLabel("PassWord: ");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 20));
lblPassword.setBounds(160, 72, 140, 40);
frame.getContentPane().add(lblPassword);
JButton Loginbtn = new JButton("Login");
Loginbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select * from Users where nickname=? and password=?";
PreparedStatement pst = connected.prepareStatement(query);
pst.setString(1, UsernameFiled.getText());
pst.setString(2, passwordField.getText());
ResultSet res = pst.executeQuery();
Firstname = res.getString("Firstname");
Lastname = res.getString("Lastname");
int c=0;
while(res.next()) {
c++;
}
if(c == 0) {
JOptionPane.showMessageDialog(null, "You didnt put any username or password!");
}
else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage();
UserFrame.setVisible(true);
}else if( c > 1) {
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}else {
JOptionPane.showMessageDialog(null, "Username and Password are inncorect...Try agian!");
}
pst.close();
res.close();
}catch(Exception LoginError) {
JOptionPane.showMessageDialog(null, LoginError);
}
}
});
Loginbtn.setFont(new Font("Tahoma", Font.BOLD, 20));
Loginbtn.setBounds(160, 148, 186, 40);
frame.getContentPane().add(Loginbtn);
UsernameFiled = new JTextField();
UsernameFiled.setFont(new Font("Tahoma", Font.BOLD, 16));
UsernameFiled.setBounds(310, 28, 186, 25);
frame.getContentPane().add(UsernameFiled);
UsernameFiled.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.BOLD, 16));
passwordField.setBounds(310, 84, 186, 25);
frame.getContentPane().add(passwordField);
MainLogo = new JLabel("");
Image imgs = new ImageIcon(this.getClass().getResource("/login.png")).getImage();
MainLogo.setIcon(new ImageIcon(imgs));
MainLogo.setBounds(10, 11, 128, 128);
frame.getContentPane().add(MainLogo);
}
}
The Welcome Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UserPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserPage frame = new UserPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connected=null;
private JTable table;
public UserPage() {
connected=DBConnection.DBPreconnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 576, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton bntLoadData = new JButton("Show Users Data");
bntLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select ID,Age,Password,Firstname,Lastname from users";
PreparedStatement pst = connected.prepareStatement(query);
ResultSet res = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(res));
} catch (Exception Error) {
Error.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Hello, " + "The Username name");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
lblNewLabel.setBounds(10, 11, 280, 19);
contentPane.add(lblNewLabel);
bntLoadData.setFont(new Font("Tahoma", Font.BOLD, 20));
bntLoadData.setBounds(162, 102, 238, 23);
contentPane.add(bntLoadData);
table = new JTable();
table.setBounds(28, 136, 508, 221);
contentPane.add(table);
}
}
In your code, you does not seem to load the username or password of the logged in user at the welcome frame. Either you will have to pass that from the login frame or you will have to re-query the database and get firstname and lastname.
I suggest, simply pass the firstname and lastname from welcome screen via constructor.
In successful login, simply pass the name in the constructor: Login code addition:
} else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage( Firstname, Lastname );
UserFrame.setVisible(true);
}
In the welcome frame, add a constructor to handle this:
public UserPage(String loggedInFirstName, String loggedInLastName){
// your remaining code
JLabel lblNewLabel = new JLabel("Hello, " + loggedInFirstName + " " + loggedInLastName );
// your remaining code.
}
A approach like this might work for your case and don't forget to mark the answer as accepted if this works for you
I have this part of code here, but whenever I launch the program I only get left brain. even though I check one or the other box.
chckbxMusic = new JCheckBox("Music");
chckbxMusic.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMath.setSelected(false);
}
});
chckbxMusic.setBounds(46, 107, 85, 23);
Question_1.add(chckbxMusic);
chckbxMath = new JCheckBox("Math");
chckbxMath.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
chckbxMusic.setSelected(false);
}
});
chckbxMath.setBounds(243, 107, 128, 23);
Question_1.add(chckbxMath);
if(chckbxMusic.isSelected()) brain_right++;
else brain_left++;
Ok maybe the full code can help a bit more..
I rewrite it a little bit, but the result is always 0 for both variables??
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class PrgVeloce {
private JFrame frame;
private JPanel Question;
private JPanel Result;
public int brain_left;
public int brain_right;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
PrgVeloce window = new PrgVeloce();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public PrgVeloce() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
Question = new JPanel();
frame.getContentPane().add(Question, "name_971195205673");
Question.setLayout(null);
final JCheckBox chckbxMath = new JCheckBox("Math");
chckbxMath.setBounds(39, 115, 128, 23);
Question.add(chckbxMath);
final JCheckBox chckbxMusic = new JCheckBox("Music");
chckbxMusic.setBounds(237, 115, 128, 23);
Question.add(chckbxMusic);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(chckbxMusic.isSelected())
{
brain_left = 10;
}
if(chckbxMath.isSelected())
{
brain_right = 10;
}
Question.setVisible(false);
Result.setVisible(true);
}
});
btnNext.setBounds(158, 210, 117, 29);
Question.add(btnNext);
Result = new JPanel();
frame.getContentPane().add(Result, "name_978670915264");
Result.setLayout(null);
JLabel lblEmisferoDx = new JLabel("Right brain:");
lblEmisferoDx.setBounds(90, 118, 110, 16);
Result.add(lblEmisferoDx);
JLabel lblNewLabel = new JLabel("Left Brain:");
lblNewLabel.setBounds(90, 157, 84, 16);
Result.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel(brain_right + "%");
lblNewLabel_1.setBounds(218, 118, 61, 16);
Result.add(lblNewLabel_1);
JLabel lblNewLabel_2 = new JLabel(brain_left + "%");
lblNewLabel_2.setBounds(218, 157, 61, 16);
Result.add(lblNewLabel_2);
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
My setter test value is the passed arguement. When I try to get it in the getter method, it returns null. I can not figure this out for the life of me.
Here is my full code. I think it may be outside of the method issue.
package com.graphics.tyler;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainFrame extends JFrame {
private JPanel contentPane;
private JPasswordField txtPassword;
private JTextField txtUsername;
//private String email;
private String test;
public String getLoggedEmail() {
System.out.println("Get logged email is: " + test);
return this.test;
}
public void setLoggedEmail(String passedName) {
System.out.println("Passed argument is: " + passedName);
this.test = passedName;
System.out.println("Setter Username is: " + test);
}
/**
* Create the frame.
*/
public MainFrame() {
Driver drive = new Driver();
setTitle("Graphics project");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(300, 30, 800, 600);
contentPane = new JPanel();
contentPane.setBackground(Color.LIGHT_GRAY);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblWelcomeToGraphics = new JLabel("Welcome to Graphics program");
lblWelcomeToGraphics.setFont(new Font("Tahoma", Font.PLAIN, 27));
lblWelcomeToGraphics.setBounds(208, 11, 360, 33);
contentPane.add(lblWelcomeToGraphics);
JButton btnExit = new JButton("Exit");
btnExit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
dispose();
}
});
btnExit.setBounds(703, 11, 71, 23);
contentPane.add(btnExit);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblUsername.setBounds(60, 199, 97, 25);
contentPane.add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblPassword.setBounds(66, 281, 91, 25);
contentPane.add(lblPassword);
txtPassword = new JPasswordField();
txtPassword.setBounds(159, 284, 193, 20);
contentPane.add(txtPassword);
txtUsername = new JTextField();
txtUsername.setBounds(159, 205, 193, 20);
contentPane.add(txtUsername);
txtUsername.setColumns(10);
JLabel lblDontHaveAn = new JLabel("Dont have an account? Sign Up!");
lblDontHaveAn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
UserCreation userCreate = new UserCreation();
dispose();
userCreate.setVisible(true);
}
});
lblDontHaveAn.setBounds(601, 536, 193, 14);
contentPane.add(lblDontHaveAn);
JButton btnSignIn = new JButton("Sign In!");
btnSignIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String email = txtUsername.getText();
String password = new String(txtPassword.getPassword());
int password1 = password.hashCode();
String password2 = Integer.toHexString(password1);
if(drive.signIn(email, password2)) {
System.out.println("Login Sucessful!");
UserScreen nextScreen = null;
setLoggedEmail(email);
try {
nextScreen = new UserScreen();
} catch (Exception e1) {
e1.printStackTrace();
}
nextScreen.setVisible(true);
dispose();
}else{
JOptionPane.showMessageDialog(null, "Email or password is incorrect");
}
}
});
btnSignIn.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnSignIn.setBounds(208, 342, 97, 33);
contentPane.add(btnSignIn);
}
}
This is the class where I call the getter method in:
public UserScreen() throws Exception {
Driver drive = new Driver();
MainFrame mainFrame = new MainFrame();
drive.getUserInfo(mainFrame.getLoggedEmail());
System.out.println("User screen email is: " + mainFrame.getLoggedEmail());
public UserScreen() throws Exception {
Driver drive = new Driver();
MainFrame mainFrame = new MainFrame(); // You instantiate new MainFrame
drive.getUserInfo(mainFrame.getLoggedEmail());
System.out.println("User screen email is: " + mainFrame.getLoggedEmail());
You instantiate a new MainFrame thats why you get null on mainFrame.getLoggedEmail().
you need to set the value in the same object you created. not the one you newly created.
I think you are calling getter method first and then the setter.
see below code sample. This will execute and give correct result.
String test;
public static void main(String []args){
HelloWorld h = new HelloWorld();
System.out.println("Hello World");
h.setLoggedEmail("HI");
h.getLoggedEmail();
}
public void setLoggedEmail(String passedName) {
System.out.println("Passed argument is: " + passedName);
this.test = passedName;
System.out.println("Username is: " + test);
}
public String getLoggedEmail() {
System.out.println("Get logged email is: " + test);
return this.test;
}
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.
I have created a JFrame with cardLayout and the first visible JPanel has a Jbutton that I have added an action Listener to perform an action. The action creates a String variable 'hhhhh' that I want to use in another JPanel. This is what I have problem doing.
Class 1
import java.awt.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class NHome extends JFrame{
JPanel Bucket= new JPanel(), Start= new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn= new JButton("Start"), mnbtn= new JButton("Manager"), csbtn= new JButton("Cashier");
CardLayout cl= new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
String hhhhh=new String("Peter");
System.out.println(hhhhh);
}
});
stbtn.setBounds(353, 245, 76, 23);
Start.add(stbtn);
Start.add(textField);
passwordField = new JPasswordField();
passwordField.setBounds(322, 183, 158, 31);
Start.add(passwordField);
Cashier.setLayout(null);
csbtn.setBounds(197, 139, 116, 23);
Cashier.add(csbtn);
Manager.setBackground(Color.BLUE);
Manager.add(mnbtn);
cl.show(Bucket, "1");
setTitle("NOVA PHARM");
getContentPane().add(Bucket);
setBounds(300, 300, 566, 482);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new CardLayout(5, 5));
setResizable(true);
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
NHome window = new NHome();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
/*
*this is the second class where I want to use the variable
*/
Class 2
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
/**
* Create the panel.
*/
public csView() {
setLayout(null);
/**
* I want to display the String hhhhh in the JLabel Uniqlbl below
*
*/
JLabel Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
}
Try modify the csView
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.Font;
public class csView extends JPanel {
// Declare those variables here
String hhhhh;
JLabel Uniqlbl;
public csView() {
setLayout(null);
Uniqlbl = new JLabel("Cashier Name:");
Uniqlbl.setFont(new Font("Tahoma", Font.PLAIN, 16));
Uniqlbl.setBounds(227, 62, 253, 46);
add(Uniqlbl);
}
// Add a setter here
public void setHhhhh(String hhhhh) {
this.hhhhh = hhhhh;
// Edit: Add this line to update the Uniqlbl text
Uniqlbl.setText(hhhhh);
}
}
And in the ActionListener call the setHhhhh() method
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
String hhhhh=new String("Peter");
// Call the setter here
Cashier.setHhhhh(hhhhh);
System.out.println(hhhhh);
}
});
I suggest you not to use the "hhhhh" variable in the csView constructor or you could stumble in a NullPointerException. Or, if you want to do so, initialize the "hhhhh" variable first like this
String hhhhh = "";
One way you could do this is a create a static variable in your NHome class that acts as a global variable. This would mean than csView would be able to read and write to the variable.
This is an example of how it could be implemented:
JPanel Bucket = new JPanel(), Start = new JPanel(), Cashier = new csView(), Manager = new JPanel();
JButton stbtn = new JButton("Start"), mnbtn = new JButton("Manager"), csbtn = new JButton("Cashier");
CardLayout cl = new CardLayout();
private final JTextField textField = new JTextField();
private JPasswordField passwordField;
static String hhhhh; //create the variable here
public NHome() {
textField.setBounds(322, 141, 158, 31);
textField.setColumns(10);
Bucket.setLayout(cl);
Bucket.add(Start, "1");
Bucket.add(Cashier, "2");
Bucket.add(Manager, "3");
Start.setLayout(null);
stbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cl.show(Bucket, "2");
/*
* I want to use this value of this String in the another class (csView)
*/
hhhhh = new String("Peter"); //set the value here
System.out.println(hhhhh);
}
});
So then you could implement it in your csView by saying:
JLabel Uniqlbl = new JLabel(NHome.hhhhh);