如何在 Java 中實施一個計算數字的程式?


該程式使用一個JLabel 元件來保留計數標籤,使用一個JTextField 元件來保留計數count,使用一個JButton 元件來建立addremove 和reset 按鈕。當我們單擊“add”按鈕時,JTextField 中的計數將+'1' 進行遞增,而單擊“remove”按鈕會將計數- '1' 進行遞減。如果我們單擊“Reset”按鈕,它將重置計數為'0'

示例

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();
   }
}

輸出

更新日期:2020 年 2 月 10 日

1K+ 瀏覽量

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告