ActionListener不能在Java中工作

时间:2013-09-06 11:00:52

标签: java swing actionlistener

我在JFrame上创建了一个JPanel,并在JPanel中添加了一个JButon和JLabel。但是ActionlListener似乎不起作用。当我点击JButton时,Nothing Happens。请有人帮助我。提前致谢。 这是我的代码

public class Trials implements ActionListener {

    JButton scoreButton;
    JLabel score;
    JPanel MyPanel;
    int ScoreAmount=0;

    public JPanel createPanel()
    {
        JPanel MyPanel =new JPanel();
        MyPanel.setLayout(null);
        MyPanel.setSize(50, 50);
        MyPanel.setBackground(Color.cyan);
        JLabel score =new JLabel(""+ScoreAmount);
        score.setSize(50, 50);
        score.setLocation(250,50);
        score.setForeground(Color.red);
        MyPanel.add(score);         
        JButton scoreButton =new JButton("add");
        scoreButton.setSize(100, 50);
        scoreButton.setLocation(100,50);
        scoreButton.setBackground(Color.red);
        scoreButton.addActionListener(this);
        MyPanel.add(scoreButton);           
        MyPanel.setOpaque(true);
        MyPanel.setVisible(true);
        return MyPanel;         
    }

    public void actionPerformed(ActionEvent e)
    {
      if(e.getSource()==scoreButton)
      {
            ScoreAmount = ScoreAmount+1;
            score.setText(""+ScoreAmount);              
      }
    }

    public static void display()
    {
        JFrame MyFrame = new JFrame();
        Trials tr =new Trials();
        MyFrame.setContentPane(tr.createPanel());
        MyFrame.setSize(500, 500);
        MyFrame.setVisible(true);
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable(){
        public void run(){
            display();
                        }
                });
        }    
}

2 个答案:

答案 0 :(得分:3)

您遮蔽为public class Trials implements ActionListener {

声明的局部变量
JButton scoreButton;
JLabel score;
JPanel MyPanel;
int ScoreAmount=0;

应该在public JPanel createPanel()

MyPanel = new JPanel();
score = new JLabel("" + ScoreAmount);
scoreButton = new JButton("add");

不是

JPanel MyPanel = new JPanel();
JLabel score = new JLabel("" + ScoreAmount);
JButton scoreButton = new JButton("add");

  • 删除MyPanel.setLayout(null);FlowLayout中默认执行的默认JPanel默认执行此操作,然后仅将JComponents添加到JPanel MyPanel.add(componentVariable)没有任何sizing JPanel个孩子

  • 致电MyFrame.pack()而非MyFrame.setSize(500, 500);

答案 1 :(得分:0)

定义分数按钮时,不指定类级别字段,而是创建新的局部变量。

JButton scoreButton =new JButton("add");
scoreButton.setSize(100, 50);
scoreButton.setLocation(100,50);
scoreButton.setBackground(Color.red);
scoreButton.addActionListener(this);
MyPanel.add(scoreButton);

应该成为:

this.scoreButton =new JButton("add");
scoreButton.setSize(100, 50);
scoreButton.setLocation(100,50);
scoreButton.setBackground(Color.red);
scoreButton.addActionListener(this);
MyPanel.add(scoreButton);

因此,当调用actionPerformed方法时,scoreButton可能为null