java - 我在哪里实现我的功能?

标签 java swing oop calculator

我正在尝试与 Java Swing 一起练习我的 OOP 技能,但目前陷入困境。我正在尝试制作一个类似于您在手机上看到的计算器图形用户界面。我不知道应该如何实现每个按钮按下的功能。现在,我只是尝试在按下按钮时在屏幕上显示数字(JLabel 对象)。我还附上了一张迄今为止我拥有的 GUI 的图片。

我应该在单独的 .java 文件中实现这些功能吗?或者它们应该在 Calculator.java 或 Keyboard.java 文件中实现?

此外,它们是如何实现的,因为如果我的按钮对象位于 Keyboard.java 文件中,我不知道如何在 Calculator.java 文件中的 JLabel 对象上显示。

计算器.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);
    }

}

键盘.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) {

    }
}

enter image description here

最佳答案

使用MVC模式并将逻辑代码放入 actionPerformed(...)方法(或任何与此相关的逻辑代码)到 Controller 类中的相应方法中。

<小时/>

MVC模式由三个类组成, Model , View ,和Control ,它们一起制作一个 GUI。

MVC 的简要摘要模式,最初取自 this answer ,但稍作修改:

  1. You’re the user — you interact with the view. The controller takes your actions and interprets them. If you click on a button, it’s the controller’s job to figure out what that means and how the model should be manipulated based on that action.
  2. The controller asks the model to change its state. When the controller receives an action from the view, it may need to tell the view to change as a result. For example, the controller could enable or disable certain buttons or menu items in the interface.
  3. The model notifies the view when its state has changed. When something changes in the model, based either on some action you took (like clicking a button) or some other internal change (like the next song in the playlist has started), the model notifies the view that its state has changed.
  4. The controller may also ask the view to change.
  5. The view asks the model for its state. The view gets the state it displays directly from the model. For instance, when the model notifies the view that a new song has started playing, the view requests the song name from the model and displays it. The view might also ask the model for state as the result of the controller requesting some change in the view.

MVC 的更详细和深入的解释模式可以在上面的链接中找到,on Oracle's website ,并通过简单的 Google 搜索即可。

<小时/>

我选择使用the observer pattern用于我的模型 View 交互。

使用 MVC 的程序示例结构:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

class Test {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                final Model model = new Model();
                final Control control = new Control(model);
                final View view = new View(model, control);

                final JFrame frame = new JFrame("MVC Example");
                frame.getContentPane().add(view);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }

        });
    }

    static class Model extends Observable {

        private int number;

        void setNumber(int newValue) {
            number = newValue;
            setChanged();
            notifyObservers(number);
        }

        int getNumber() {
            return number;
        }

    }

    static class View extends JPanel {

        View(Model model, Control control) {
            final JLabel label = new JLabel(Integer.toString(model.getNumber()));
            final JButton button = new JButton("Click me!");
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    control.buttonPressed();
                }

            });

            setLayout(new BorderLayout());
            add(label);
            add(button, BorderLayout.SOUTH);

            model.addObserver(new Observer() {

                @Override
                public void update(Observable o, Object arg) {
                    label.setText(Integer.toString((int) arg));
                }

            });
        }

    }

    static class Control {

        private Model model;

        Control(Model model) {
            this.model = model;
        }

        void buttonPressed() {
            model.setNumber(model.getNumber() + 1);
        }

    }

}

代码注释:

  • 看看arraysfor loop帮助您简化按钮的声明。
  • 而不是设置您的 JFrame s尺寸,请调用pack()在您的JFrame上添加所有组件以适合您的 JFrame 后适合其子级的大小。
  • 不要延长 JFrame ,而是创建一个实例并进行必要的修改。
  • EDT 上运行您的代码(事件调度线程)以避免 GUI 中“卡住”。欲了解更多信息,请查看The Java™ Tutorials - Concurrency in Swing
  • 下次发帖时请考虑发帖,为了更快获得更好的帮助,请发帖 MCVE .

关于java - 我在哪里实现我的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41353922/

相关文章:

java - 在 Java 脚本中在 Rhino 解释器中实例化抽象类

java - 本地化 org.apache.wicket.extensions.yui.calendar.DatePicker 中的标签

java - 调用返回 null 的 getGraphics() 的任何替代方法

oop - 关联端如何在 UML 中为关联所有且可导航?

c# - 多继承无多重继承无代码重复

java - 无法编译简单的java小程序

java - 不可见的 JRadioButtons

java - 如何在 JTextArea 中编写内容并在不按任何按钮的情况下显示它

java - 在 java swing 中使用 jTable 的论坛主题 View

ruby-on-rails - 如何禁用 Rails 应用程序中的迁移功能?