我刚刚了解了 ActionListener
,我的任务是使用与 JLabel
关联的 JButton
创建一个简单的应用程序int
每次被点击时值增加 1。这是我的编码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonPanel2 extends JPanel implements ActionListener {
JButton button2;
JLabel secondLabel;
int i = 1;
int total = 0;
ButtonPanel2()
{
button2 = new JButton("Push");
add(button2);
button2.addActionListener(this);
secondLabel = new JLabel("Button pushes: " + total);
add(secondLabel);
}
public void actionPerformed(ActionEvent e)
{
total += i;
}
}
和驱动类:
import java.awt.*;
import javax.swing.*;
class TestButtonPanel2 {
public static void main(String [] args)
{
JFrame buttonFrame2 = new JFrame("Button Panel 2");
ButtonPanel2 panel2 = new ButtonPanel2();
buttonFrame2.add(panel2);
buttonFrame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buttonFrame2.setSize(400 , 400);
buttonFrame2.setVisible(true);
}
}
提前致谢! :)
最佳答案
在 ActionListener
中,像这样更新 GUI:
public void actionPerformed(ActionEvent e)
{
total += i;
secondLabel.setText("Button pushes: " + total);
}
关于java - 每次单击 JButton 时如何将值增加 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24741283/