I am relativley new to the exposure of the Java Language and was pondering about my lines of code that I have written. To summarize my goals at the end of this question I would like to have assistance on achieving a JButton that contains an ActionListener with 'If'to run a class that is on a different file in the same directory.(The 'Else' function is working fine, its the 'If'). (I have 2 files, one being main.java and the other being home.java(I am using Eclipse IDE)(The problem for me occurs at the JButton where I dispose main to close that and attempt to run the class file.)
Here is home.java:
import javax.swing.*;
import java.awt.*;
public class home {
public static void main(String[] args) {
JFrame h = new JFrame("Welcome - LonelyChat v1.0");
h.setResizable(false);
h.setSize(500, 500);
h.setDefaultCloseOperation(h.EXIT_ON_CLOSE);
}
}
Here is main.java (Not all the code, only the main important lines):
//Username login field
JTextField username = new JTextField("Username", 20);
//Password login field
JPasswordField password = new JPasswordField("Password", 20);
//Main window frame
JFrame main = new JFrame("Window");
main.setDefaultCloseOperation(main.EXIT_ON_CLOSE);
main.setVisible(true);
main.setSize(500, 500);
main.setLocationRelativeTo(null);
main.setResizable(false);
//Login Button
JButton login = new JButton("Login");
login.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String uname=username.getText();
String psw=password.getText();
if(uname.equals("lonely") && psw.equals("pass"))
{
JOptionPane.showMessageDialog(main,"Succuess! Now logged in!");
// logged in
main.dispose();
}
else
{
JOptionPane.showMessageDialog(main,"Failed! Wrong Username or Password!");
}
}
});
Basically I am having trouble on running a separate class in a different java file with a JButton with If and else. I have tried things such as:
example ex = new example();
ex.setVisible(true);
( Method 1 /\ and Method 2 / )
ex1.dispose(); //this method works but I do not want another JFrame in the
ex2.setVisible(true); //same file
Aucun commentaire:
Enregistrer un commentaire