【发布时间】:2016-12-28 00:37:07
【问题描述】:
我正在尝试与 Java Swing 一起练习我的 OOP 技能,但我目前陷入困境。我正在尝试制作一种类似于您在手机上看到的计算器 gui。我不知道我应该如何实现每个按钮按下的功能。现在我只是想在按下按钮时在屏幕上显示数字(JLabel 对象)。我还附上了一张我目前拥有的 GUI 的图片。
我应该在单独的 .java 文件中实现这些功能吗?还是应该在 Calculator.java 或 Keyboard.java 文件中实现它们?
它们是如何实现的,因为如果我的按钮对象在 Keyboard.java 文件中,我不知道如何在 Calculator.java 文件中的 JLabel 对象上显示。
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/-+]按钮将是相同的,将按钮的符号附加到表达式并更新显示的字符串。其余的按钮显然有不同的用途,需要自定义动作监听器。 -
另见calculator example。它使用
ScriptEngine来评估文本字段中的表达式。
标签: java swing oop calculator