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 }

  • 相关阅读:
    理解scrollTop,scrollLeft,clientWidth,clientHeight,offsetWidth,offsetHeight
    jQuery插件开发全解析
    JavaScript世界的一等公民 函数
    js 判断键盘事件大全 兼容FireFox和IE(退格、制表、回车、空格、方向键、删除键等)
    使用SeaJS实现模块化JavaScript开发
    嵌套iframe下父子页面之间的同域与跨域通信
    PHP设计模式(一)
    获取Form多条选中记录
    AX Barcode
    AX Query分页
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/4754067.html
Copyright © 2011-2022 走看看