Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để thực hiện một chương trình để đếm số trong Java?


Chương trình sử dụng JLabel để giữ một nhãn đếm, một JTextField thành phần để giữ số đếm , JButton thành phần để tạo thêm , loại bỏ đặt lại nút. Khi chúng tôi nhấp vào nút thêm, số lượng trong JTextField sẽ được tăng lên bởi '1' và bằng cách nhấp vào nút xóa, số lượng sẽ được giảm đi bởi '1'. Nếu chúng tôi nhấp vào nút Đặt lại, nó sẽ đặt lại số đếm thành ' 0' .

Ví dụ

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CounterTest extends JFrame implements ActionListener {
   private JLabel label;
   private JTextField text;
   private JButton addBtn, removeBtn, resetBtn;
   private int count;
   public CounterTest() {
      setTitle("Counter Test");
      setLayout(new FlowLayout());
      count = 0;
      label = new JLabel("Count:");
      text = new JTextField("0", 4);
      addBtn = new JButton("Add");
      removeBtn = new JButton("Remove");
      resetBtn = new JButton("Reset");
      addBtn.addActionListener(this);
      removeBtn.addActionListener(this);
      resetBtn.addActionListener(this);
      add(label);
      add(text);
      add(addBtn);
      add(removeBtn);
      add(resetBtn);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public void actionPerformed(ActionEvent ae) {
      if (ae.getSource() == addBtn) {
         count++; // increment the coiunt by 1
         text.setText(String.valueOf(count));
         repaint();
      } else if (ae.getSource() == removeBtn) {
         count--; // decrement the count by 1
         text.setText(String.valueOf(count));
         repaint();
      } else if (ae.getSource() == resetBtn) {
         count = 0; // reset the count to 0
         text.setText(String.valueOf(count));
         repaint();
      }
   }
   public static void main(String[] args) {
      new CounterTest();
   }
}

Đầu ra

Làm thế nào để thực hiện một chương trình để đếm số trong Java?