Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

alternatives to using ".this" for addActionListener? static context issues

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
  } 
} );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading