首页 > 解决方案 > com.company.Main.this' 不能从静态上下文中引用

问题描述

为什么它不起作用?我有四个类,主类、“MyFrame”类、“MyButton”类和 MySecondFrame 类。如果用户单击按钮,第一帧应该消失,第二帧应该出现“(它是无法解决方法中的符号错误。单击)。还有错误“'com.company.Main.this' cannot be从静态上下文引用(在主方法的第二行中)“。我该如何解决这个问题?这是我的代码:

package com.company;

interface ButtonListener{
void onClick();
}

public class Main implements ButtonListener {

public static void main(String[] args) {


    MyFrame firstFrame = new MyFrame();
    MyButton firstButton = new MyButton(this);
    //MyTextField firstTextField = new MyTextField();
    MySecondFrame secondFrame = new MySecondFrame();
    MyLabel firstLabel = new MyLabel();
    firstFrame.add(firstButton);
    //secondFrame.add(firstTextField);
    //secondFrame.add(firstLabel);
}

@Override
void onClick() {
    firstFrame.setVisible(false);
    secondFrame.setVisible(true);
}

}

package com.company;
import javax.swing.*;
import java.awt.*;

public class MyFrame extends JFrame{

MyFrame(){
    this.getContentPane().setBackground(new Color(0xD3D3D3));
    this.setSize(500, 700);
    this.setLocation(870,15);
    this.setResizable(false);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    this.setTitle("Converter");
    this.setLayout(null);
}

}

package com.company;

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

public class MyButton extends JButton implements ActionListener{

private ButtonListener buttonListener;



MyButton(ButtonListener buttonListener){
    this.buttonListener = buttonListener;
    this.setBounds(150, 100, 200, 50);
    this.setText("Convert Currencies");
    this.setFocusable(false);
    this.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e){
    if(e.getSource()==this){
        buttonListener.onClick();
    }
    }

}

package com.company;

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

public class MySecondFrame extends JFrame {
MySecondFrame(){
    this.getContentPane().setBackground(new Color(0xD3D3D3));
    this.setSize(500, 700);
    this.setLocation(870,15);
    this.setResizable(false);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
    this.setTitle("Converter");
    this.setLayout(null);
}

}

标签: java

解决方案


instanceMain解决方案1:在类中声明一个实例方法Main,并更改您的main方法以创建一个Main对象并调用其instanceMain

public void instanceMain() {
    // Move your code from your existing main() method to this method
}
public static void main(String[] args) {
    // Move your existing code out of main() and replace it with this:
    Main inst = new Main();
    inst.instanceMain();
}

解决方案 2:在您的main方法中,更改

MyButton firstButton = new MyButton(this);

MyButton firstButton = new MyButton(new Main());

推荐阅读