我一直在努力解决我的代码几个小时,我仍然无法摆脱这个错误。在下面的代码中,One.addActionListener(this)
和Two.addActionListener(this)
都在this
的下方有红线,表示'不能在静态上下文中使用它'。如果可以,请帮助我。谢谢!Java中的ActionListener问题
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TheMain extends JFrame implements ActionListener, WindowListener {
int input1 = 0;
int input2 = 0;
public static void main(String[] args) {
TheMain main = new TheMain();
JButton One = new JButton("1");
One.setSize(10, 10);
One.addActionListener(this);
JButton Two = new JButton("2");
Two.setSize(10, 10);
Two.addActionListener(this);
}
public TheMain(){
JButton One = new JButton("1");
One.setSize(10, 10);
One.addActionListener(this);
JButton Two = new JButton("2");
Two.setSize(10, 10);
Two.addActionListener(this);
JFrame frame = new JFrame("window");
frame.setSize(200, 250);
frame.setVisible(true);
frame.add(One);
frame.add(Two);
}
public void actionPerformed(ActionEvent e) {
if(input1 != 0){
if(input2 != 0){
System.out.println("Max 2 numbers!");
}else{
input2 = 1;
}
}else{
input1 = 1;
}
}
public void actionPerformed1(ActionEvent e) {
if(input1 != 0){
if(input2 != 0){
System.out.println("Max 2 numbers!");
}else{
input2 = 2;
}
}else{
input1 = 2;
}
}
@Override
public void windowOpened(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
}
了解更多关于面向对象的编程。 'this'必须指向静态上下文中没有实例的当前类的实例。 –
只需在''this'处写'main'来代替'this',因为您已经在'main'方法内引用了该类:-) –
您已经在构造函数中创建按钮,那么为什么要再次创建它们?你的类扩展了JFrame,所以你为什么要创建一个新的JFrame来添加按钮? – ChadNC