【问题标题】:Non-static variable this cannot be referenced from a static context JFrame非静态变量 this 不能从静态上下文 JFrame 中引用
【发布时间】:2014-08-25 14:23:42
【问题描述】:

我有这个代码:

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

我想在名为

的 JButton 中添加一个动作监听器
printButton

我也有一个 JFrame

inputFrame

这在我的 Main

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

但我不断收到此错误:

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

我该怎么做?如果你们能在不使用匿名内部课程的情况下帮助我,那就太好了。(我的老师还没有教我们那节课)。谢谢!

【问题讨论】:

  • 我们需要看到整个班级来诊断您的问题。理想情况下,您应该先从代码中消除不必要的细节,然后再给出一个简短的示例让我们重现问题。
  • 你可以让你的方法是非静态的。
  • 您可以将 printButton 和 inputFrame 设为静态(更简单),或者将您的静态方法转换为非静态方法,初始化您的类的实例,然后调用您的方法。

标签: java swing constructor static jframe


【解决方案1】:

以下代码导致问题。

 printButton.addActionListener(this);

原因:
inputGUI() 是静态的,因此使用引用当前对象的this 关键字被拒绝。

解决方案:
只需创建一个新的类对象来处理printButton 的点击事件。说 MainClass 对此负责。更改您的代码如下:

 printButton.addActionListener(new MainClass());

替代解决方案:
使inputGUI() 非静态。并从 main 方法中调用它为new MainClass().inputGUI()。休息保持不变。

【讨论】:

    【解决方案2】:
    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();   
        }
    }
    

    你的意思是这样的?

    【讨论】:

      猜你喜欢
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      • 2011-11-30
      相关资源
      最近更新 更多