我已经尝试修复我的代码几个小时,但我仍然无法摆脱这个错误。在下面的代码中,在“不能在静态上下文中使用它”One.addActionListener(this)
下方Two.addActionListener(this)
都有红线。this
如果可以的话,请帮助我。谢谢!
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
}
}