我正在嘗試與Java Swing一起練習我的OOP技能,但我目前被卡住了。我正在嘗試製作一個計算器,類似於你在手機上看到的計算器。我不知道我應該如何實現每個按鈕的功能。現在我只是試圖在按下按鈕時在屏幕上顯示數字(JLabel對象)。我還附上了迄今爲止我所用的GUI的圖片。我在哪裏實現我的功能?
我應該在單獨的.java文件中實現這些功能嗎?還是應該在Calculator.java或Keyboard.java文件中實現它們?
它們是如何實現的,因爲我不知道如何在Calculator.java文件中的JLabel對象上顯示,如果我的按鈕對象在Keyboard.java文件中的話。
Calculator.java
package calculator;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculator extends JFrame
{
public static void main(String[] args)
{
new Calculator();
}
public Calculator() //Calculator constructor??
{
setLayout(new GridLayout(2,1));
this.setSize(400,600);
this.setLocationRelativeTo(null); //center the window
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel display = new JLabel();
this.add(display);
Keyboard kb = new Keyboard();
this.add(kb);
this.setVisible(true);
}
}
Keyboard.java
package calculator;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Keyboard extends JPanel implements ActionListener
{
public Keyboard()
{
setLayout(new GridLayout(4,4));
JButton one = new JButton("1");
this.add(one);
JButton two = new JButton("2");
this.add(two);
JButton three = new JButton("3");
this.add(three);
JButton plus = new JButton("+");
this.add(plus);
JButton four = new JButton("4");
this.add(four);
JButton five = new JButton("5");
this.add(five);
JButton six = new JButton("6");
this.add(six);
JButton minus = new JButton("-");
this.add(minus);
JButton seven = new JButton("7");
this.add(seven);
JButton eight = new JButton("8");
this.add(eight);
JButton nine = new JButton("9");
this.add(nine);
JButton times = new JButton("x");
this.add(times);
JButton zero = new JButton("0");
this.add(zero);
JButton clear = new JButton("clear");
this.add(clear);
JButton equals = new JButton("=");
this.add(equals);
JButton divide = new JButton("/");
this.add(divide);
}
public void actionPerformed(ActionEvent e) {
}
}
按下按鈕是做什麼的?如果你只是構造一個表達式以便稍後評估並將其顯示給用戶,那麼處理'[0-9x/- +]'按鈕將是相同的,將該按鈕的符號追加到表達式並更新顯示的字符串。其餘按鈕明顯用於不同的目的,並需要自定義動作監聽器。 – dramzy
另請參閱此[計算器示例](http://stackoverflow.com/a/7441804/418556)。它使用'ScriptEngine'來評估文本字段中的表達式。 –