zoukankan      html  css  js  c++  java
  • JButton计数

    1.引言

    在Swing窗口中,我们时常会点击按钮进行计数,例如点击按钮A,第一次弹出窗口1,第二次弹出窗口2....以及按钮的快捷键设置。

     1 import java.awt.event.ActionEvent;
     2 import java.awt.event.ActionListener;
     3 import java.awt.event.KeyEvent;
     4 import javax.swing.JButton;
     5 import javax.swing.JFrame;
     6 import javax.swing.JLabel;
     7 public class TestCount {
     8     String sum = "Number of button clicks: ";
     9 
    10     //用于计数的count需要作为全局变量,如果在监听器中添加该变量,则会一直被初始化,cout++无效
    11     int count = 0;
    12     JFrame f = new JFrame("计数测试");
    13     JButton b1 = new JButton("click me!");
    14     JLabel l1 = new JLabel(sum+count);
    15     public TestCount() {
    16         f.setSize(300, 280);
    17         f.setResizable(false);
    18         f.setLocationRelativeTo(null);
    19         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    20         Container content=f.getContentPane();
    21         content.setLayout(null);
    22         b1.setBounds(100, 60, 100, 40);  
    23 
    24          //按钮的快捷键的设置,可以按ALT+I进行操作
    25         b1.setMnemonic(KeyEvent.VK_I); 
    26         content.add(b1);
    27         l1.setBounds(80, 200, 150, 30);
    28         content.add(l1);
    29         action();
    30         f.setVisible(true);
    31     }
    32     public void action() {
    33         b1.addActionListener(new ActionListener() {
    34             public void actionPerformed(ActionEvent e) {
    35 
    36                //如果需要弹出1,2,3等窗口,则添加if语句配合count使用,例如if(count==1){...}, else if(count==2) {...}, else{...}
    37 
    38                //如果在这里定义int count=0;会一直显示1
    39                 count++;
    40 
    41                //为了响应标签中的计数,需要在监听器中为标签设置内容,否则计数一直为0
    42                 l1.setText(sum + count);        
    43             }
    44         });
    45     }
    46     public static void main(String args[]) {
    47         new TestCount();
    48     }
    49 }

  • 相关阅读:
    Biba模型简介
    Fragment 与 Activity 通信
    小米2S 连接Ubuntu Android Studio
    【转】Android 实现“再按一次退出程序”
    取消 EditText 自动聚焦弹出输入法界面
    为Android Studio 项目手动下载gradle
    【转】Java读取文件方法大全
    sudo: /etc/sudoers 的模式为 0551,应为 0440
    Win7 下硬盘安装Linux Mint 17
    Linux Versus Windows, Ubuntu/Mint V XP/Vista/7
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/4754067.html
Copyright © 2011-2022 走看看