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