我一直在努力解決我的代碼幾個小時,我仍然無法擺脫這個錯誤。在下面的代碼中,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