1

我在 JFrame 上创建了一个 JPanel,并向 JPanel 添加了一个 JButon 和 JLabel。但是 ActionlListener 似乎不起作用。当我单击 JButton 时,什么也没有发生。请有人帮助我。提前致谢。这是我的代码

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();
                        }
                });
        }    
}
4

2 回答 2

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情况下,然后添加JComponentsJPanel只有MyPanel.add(componentVariable)没有任何sizingfor JPanels 孩子

  • 打电话MyFrame.pack()而不是MyFrame.setSize(500, 500);

于 2013-09-06T11:06:01.273 回答
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

于 2013-09-06T11:03:20.593 回答