created login class for GUI, added all the GUI construction to a method so I can call it from my main class on startup. Calling method throws error "'GUILoginPage.this' cannot be referenced from a static context".
What are the work arounds for this? I understand the reasoning behind not being able to use .this but I haven't seen any solutions
public static void main() {
JFrame frame = new JFrame();
JButton loginButton = new JButton("Login");
JTextField userIDField = new JTextField();
JPasswordField userPasswordField = new JPasswordField();
JLabel userIDLabel = new JLabel("Username:");
JLabel userPasswordLabel = new JLabel("Password:");
userIDLabel.setBounds(50, 100, 75, 25);
userPasswordLabel.setBounds(50, 150, 75, 25);
userIDField.setBounds(125, 100, 200, 25);
userPasswordField.setBounds(125, 150, 200, 25);
loginButton.setBounds(125, 200, 100, 25);
loginButton.addActionListener(this);
frame.add(userIDLabel);
frame.add(userPasswordLabel);
frame.add(userIDField);
frame.add(userPasswordField);
frame.add(loginButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(null);
frame.setVisible(true);
}
CodePudding user response:
this
doesn't have any meaning in a static context. your main is Static so it means that there is no instance of a class to work with.
Here you will need to define and use your own action listener that will handle the button click, such as :
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
performLogin();
}
} );