您好我的问题是我无法向Action侦听器添加按钮 我会做一个菜单 我不知道为什么我会成为一个错误 这里的代码 包lvl;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JFrame implements ActionListener{
private JButton button;
private JButton eintellungen;
private JButton credits;
private JButton schliessen;
public static void main(String[] args) {
JFrame meinJFrame = new JFrame();
meinJFrame.setTitle("menu");
JPanel panel = new JPanel();
JButton button = new JButton("play");
JButton schliessen = new JButton("schließen");
JButton eintellungen = new JButton("einstellungen");
JButton credits = new JButton("credits");
panel.add(button);
panel.add(schliessen);
panel.add(credits);
panel.add(eintellungen);
credits.addActionListener(this);
meinJFrame.add(panel);
meinJFrame.setSize(500, 500);
meinJFrame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
}
}
} 哦,我成为一个错误错误说不能在静态上下文中使用它,它是通过credits.addActionListener(this); 请帮帮我
答案 0 :(得分:1)
您处于public static main
的静态环境中。静态上下文中没有this
。使用被保证的自治类。
credits.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//// handle action here
}
});
答案 1 :(得分:0)
credits.addActionListener(new YourActionListener());
meinJFrame.add(panel);
meinJFrame.setSize(500, 500);
meinJFrame.setVisible(true);
}
}
class YourActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
}
}
或
credits.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});