简体   繁体   中英

Non-static variable this cannot be referenced from a static context JFrame

I have this code:

private static void inputGUI() {
    inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    inputFrame.setTitle("The INPUT");
    panel.add(printButton);
    printButton.setBounds(135,560,120,30);
    inputFrame.setLayout(null);
    inputFrame.add(panel);
    panel.setBounds(1000,100,366,768-100);

    //ActionListeners!!!    
    printButton.addActionListener(this);
    inputFrame.setSize(1366,768);
    inputFrame.setVisible(true);
}

I wanted to add an action listener to my JButton named

printButton

I also have a JFrame

inputFrame

and this in my Main

public static void main (String[] args) {
    inputGUI();
}

But I keep getting this error:

error: non-static variable this cannot be referenced from a static context

How can I do this? It would be great if you guys can help me without using an anonymous inner class.(My teacher hasn't taught us that lesson yet). Thank you!

Following code is causing the problem.

 printButton.addActionListener(this);

Reason:
inputGUI() is static as a result of which using this keyword which refers to the current object is denied.

Solution:
Simply create a new object of the class which handles the click events of printButton . Say MainClass is responsible for that. Change your code as following:

 printButton.addActionListener(new MainClass());

Alternate Solution:
Make inputGUI() non static. And call it from main method as new MainClass().inputGUI() . Rest remains same.

import java.awt.event.ActionEvent;
import javax.swing.*;

public class NewClass {


    public NewClass(){
     //inputGUI();
    }
    public static void method(){
      JOptionPane.showMessageDialog(null, "");
    }
    private static void inputGUI() {
    JFrame inputFrame = new JFrame();
    JPanel panel = new JPanel();
    JButton printButton = new JButton();
    inputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    inputFrame.setTitle("The INPUT");
            panel.add(printButton);
                printButton.setBounds(135,560,120,30);
    inputFrame.setLayout(null);
        inputFrame.add(panel);
    panel.setBounds(1000,100,366,768-100);

    //ActionListeners!!!    
        printButton.addActionListener(new java.awt.event.ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
              method();
            }
        });
inputFrame.setSize(1366,768);
inputFrame.setVisible(true);
}
    public static void main(String[]args){
     inputGUI();   
    }
}

you mean like this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM