My too simple Swing code is causing the whole system to freeze. I'm learning java still :)
this is the actionEvent
that is causing the problem
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();
System.out.println("hej");
}
I haven't wrote anything in there yet(still testing) because obviously it is in the code here in the class xD
public class NewAccount implements ActionListener {
static JFrame frame = new JFrame();
static JButton createAccountButton = new JButton();
static JButton haveAnAccount = new JButton();
static JLabel usernameLabel = new JLabel();
static JLabel passwordLabel = new JLabel();
static JTextField usernameField = new JTextField();
static JPasswordField passwordField = new JPasswordField();
NewAccount() {
frame = new JFrame();
createAccountButton = new JButton("Create account");
haveAnAccount = new JButton("Already have an account?");
usernameLabel = new JLabel("New username");
passwordLabel = new JLabel("New Password");
usernameField = new JTextField(20);
passwordField = new JPasswordField(20);
//Frame
frame.setLayout(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(400, 250);
frame.setTitle("Create new account");
//Buttons
frame.add(createAccountButton);
createAccountButton.setLocation(20, 130);
createAccountButton.setSize(230, 30);
createAccountButton.setFocusable(false);
createAccountButton.addActionListener(new NewAccount());
frame.add(haveAnAccount);
haveAnAccount.setLocation(20, 170);
haveAnAccount.setSize(230, 30);
haveAnAccount.setFocusable(false);
//Labels
frame.add(usernameLabel);
usernameLabel.setLocation(20, 20);
usernameLabel.setSize(130, 30);
frame.add(passwordLabel);
passwordLabel.setLocation(20, 50);
passwordLabel.setSize(130, 30);
//Fields
frame.add(usernameField);
usernameField.setLocation(150, 20);
usernameField.setSize(165, 25);
frame.add(passwordField);
passwordField.setLocation(150, 50);
passwordField.setSize(165, 25);
}
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();
System.out.println("hej");
}
}
I have no idea what is wrong with it but when I delete the actionlistener it works without freezing my whole system.
CodePudding user response:
createAccountButton.addActionListener(new NewAccount());
Congratulations, you created an infinite loop. That eats your memory.
Maybe you mean to pass this
?
CodePudding user response:
Change this line
createAccountButton.addActionListener(new NewAccount());
to
createAccountButton.addActionListener(this);
CodePudding user response:
Solved:
it was a simple mistake but took me so many hours that I had to make a question here. the only problem was to put this
createAccountButton.addActionListener(new NewAccount());
before setting it's bounds and location. hope if anyone had the same problem sees this.