本帖最後由 tonyh 於 2021-9-3 20:26 編輯
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class Ch83 implements ActionListener{
- JFrame fm;
- JLabel lb;
- JButton btn1, btn2;
- int n=0;
-
- Ch83()
- {
- lb=new JLabel("0");
- lb.setBounds(25, 20, 80, 15);
-
- btn1=new JButton("點擊");
- btn1.setBounds(60, 10, 80, 35);
- btn1.addActionListener(this);
- btn2=new JButton("歸零");
- btn2.setBounds(150, 10, 80, 35);
- btn2.addActionListener(this);
-
- fm=new JFrame("點擊計數器");
- fm.setBounds(100, 100, 245, 80);
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.add(lb);
- fm.add(btn1);
- fm.add(btn2);
- }
-
- public static void main(String[] args) {
- new Ch83(); //匿名
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==btn1)
- {
- n++;
- lb.setText(n+"");
- }
- if(e.getSource()==btn2)
- {
- n=0;
- lb.setText("0");
- }
- }
- }
複製代碼- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- public class Ch83{
- JFrame fm;
- JLabel lb;
- JButton btn1, btn2;
- int n=0;
- Ch83()
- {
- lb=new JLabel("0");
- lb.setBounds(25, 20, 80, 15);
- btn1=new JButton("點擊");
- btn1.setBounds(60, 10, 80, 35);
- btn1.addActionListener(new MyListener());
- btn2=new JButton("歸零");
- btn2.setBounds(150, 10, 80, 35);
- btn2.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==btn2)
- {
- n=0;
- lb.setText("0");
- }
- }
- });
- fm=new JFrame("點擊計數器");
- fm.setBounds(100, 100, 245, 80);
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.add(lb);
- fm.add(btn1);
- fm.add(btn2);
- }
- class MyListener implements ActionListener
- {
- @Override
- public void actionPerformed(ActionEvent e) {
- if(e.getSource()==btn1)
- {
- n++;
- lb.setText(n+"");
- }
- }
- }
- public static void main(String[] args) {
- new Ch83(); //匿名
- }
- }
複製代碼 |