java - 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);
}
}
解决方案
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());
推荐阅读
- authorize.net - 如何使用 Authorize.net API 检索两个日期之间所有交易的完整交易详情?
- python - 不同的输入失败后,输入提示不返回到先前的提示
- json - 如何使用 Aeson 生成文字(未引用)javascript 表达式?
- vue.js - 模块构建失败 @content($material-light) vuetify 2.3.10
- c - 处理C中字符数组的引用传递
- python - 使用python将记录附加到csv文件的开头而不将文件读入内存
- java - 通过覆盖Java中的equals()来比较Object对象和Class对象
- go - SupportsCertificate 不会为从 pfx 提取的 x509Certificate 抛出相互支持的协议版本
- r - 从另一个参考水平获取模型估计,而不运行新模型?
- c - 为什么 SDL_RenderCopy 这么长?