import java.awt.Desktop.Action;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;public class Surprise { private JLabel jlb=new JLabel("欢迎使用计数器!"); private JLabel jlb1=new JLabel(); private JPanel jp=new JPanel(); private JButton jb=new JButton("点我试试,会有惊喜哦!"); public Surprise(){ JFrame jf=new JFrame("Windows JFrame"); jf.add(jp); jp.add(jb); jp.add(jlb); jb.addActionListener(new MyActionListener() ); jf.setBounds(300, 200, 600, 200); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e){ String command=e.getActionCommand(); if(command.equals("点我试试,会有惊喜哦!")){ int num=0; num++; jp.add(jlb1); jlb1.setText("你已经点击"+num+"次了!"); } } } public static void main(String[] args) { new Surprise(); }}
1 回答

guozhchun
TA贡献103条经验 获得超76个赞
你把num的定义放在了 if 条件语句里面,这样每次点击调用actionPerformed()函数都会让num赋值为0然后在重新叠加,就造成了每次点击都是保持 1 不变。
把int num = 0 这条语句放在函数actionPerformed() 外面就可以了
添加回答
举报
0/150
提交
取消