Java帮助 - ActionListener无法正常工作

时间:2013-12-15 11:55:32

标签: java jframe jlabel

我是Java新手, 我正在尝试使静态类Action实现ActionListener 工作,但不管我做什么,它几乎都不起作用。

有人可以帮帮我吗?

 package kod.main;

 import java.awt.event.*;
 import javax.swing.*;

 public class FoodMenu {

 public static void main(String[] args) {

   //JFrame   
   JFrame frame = new JFrame ("Hello");
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(500,500);
   JPanel panel = new JPanel();
   frame.add(panel);
   JButton button = new JButton("Start Game");
   panel.add(button);
 }
 static class Action implements ActionListener{

    public void actionPreformed (ActionEvent e){
        JFrame Frame2 = new JFrame ("Clicked");
        Frame2.setVisible(true);
        Frame2.setSize(200,200);
        JLabel lable = new JLabel("Success !");
    }
  }
}

2 个答案:

答案 0 :(得分:1)

你错误拼写了界面方法......它是“actionPerformed”而不是“actionPreformed”。使用覆盖注释,它会告诉你。

@Override
public void actionPerformed(ActionEvent e) {
  JFrame Frame2 = new JFrame("Clicked");
  Frame2.setVisible(true);
  Frame2.setSize(200, 200);
  JLabel lable = new JLabel("Success !");
}

答案 1 :(得分:0)

首先,你的Action类拼写错误actionPerformed

您还没有将ActionListener的实例注册到任何组件。您可以将以下内容添加到main方法中,假设您希望在按下button时执行您所编写的操作。

button.addActionListener(new Action());