【问题标题】:Calculator GUI ActionPerformed method, and wrapping around another classCalculator GUI ActionPerformed 方法,并包装另一个类
【发布时间】:2012-11-08 03:29:56
【问题描述】:

我正在尝试将计算器 GUI 包装在我构建的一个类上,该类以不同的方式计算值(不是正常的方式,用反向波兰表示法)。

我只想知道两件事:

1) 如何编写我的 actionPerformed 方法,以便当您单击按钮或操作时,它会显示在显示屏中

2) 如何使用 GUI 和计算方法(例如如何制作,以便当您按下 GUI 上的所有数字或运算符时,它会在我的计算类中注册)。基本上如何将 GUI 包裹起来?

**编辑,我编辑了我的代码,但是当它编译时它给了我一个空指针异常,怎么会?

到目前为止我的 GUI 类:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;

public class GUI extends JFrame implements ActionListener
{
JPanel buttonPanel, topPanel, operationPanel;
JTextField display;

doMath math = new doMath();

JButton Num1;
JButton Num2;
JButton Num3;
JButton Num4;
JButton Num5;
JButton Num6;
JButton Num7;
JButton Num8;
JButton Num9;
JButton Num0;

JButton Add;
JButton Sub;
JButton Mult;
JButton Div;
JButton Eq;
JButton Clr;
public GUI()
{
    super("Calculator");
    setSize(400,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout (2,1));

    buttonPanel = new JPanel();        
    buttonPanel.setLayout(new GridLayout(4, 4));
    buttonPanel.add(Num1 = new JButton("1"));
    buttonPanel.add(Num2 = new JButton("2"));
    buttonPanel.add(Num3 = new JButton("3"));
    buttonPanel.add(Num4 = new JButton("4"));
    buttonPanel.add(Num5 = new JButton("5"));
    buttonPanel.add(Num6 = new JButton("6"));
    buttonPanel.add(Num7 = new JButton("7"));
    buttonPanel.add(Num8 = new JButton("8"));
    buttonPanel.add(Num9 = new JButton("9"));
    buttonPanel.add(Num0 = new JButton("0"));        
    buttonPanel.add(Clr = new JButton("C"));
    buttonPanel.add(Eq = new JButton("="));
    buttonPanel.add(Add = new JButton("+"));
    buttonPanel.add(Sub = new JButton("-"));
    buttonPanel.add(Mult = new JButton("*"));
    buttonPanel.add(Div = new JButton("/"));


    Num1.addActionListener(this);
    Num2.addActionListener(this);
    Num3.addActionListener(this);
    Num4.addActionListener(this);
    Num5.addActionListener(this);
    Num6.addActionListener(this);
    Num7.addActionListener(this);
    Num8.addActionListener(this);
    Num9.addActionListener(this);
    Num0.addActionListener(this);
    Clr.addActionListener(this);
    Eq.addActionListener(this);
    Add.addActionListener(this);
    Sub.addActionListener(this);
    Mult.addActionListener(this);
    Div.addActionListener(this);

    topPanel = new JPanel();         
    topPanel.setLayout(new FlowLayout());
    topPanel.add(new JTextField(20));
   //jtfResult.setHorizontalAlignment(JTextField.RIGHT);
   // jtfResult.setEditable(false);  

    add(mainPanel);

    mainPanel.add(topPanel, BorderLayout.NORTH);
    mainPanel.add(buttonPanel, BorderLayout.SOUTH);

    setVisible(true);

}

public void actionPerformed(ActionEvent e) 
{
     if(e.getSource() == Num1)
    {
        s += "1";
        display.setText(s);
    }
    if(e.getSource() == Num2)
    {
        s += "2";
        display.setText(s);
    }
    if(e.getSource() == Num3)
    {
        s += "3";
        display.setText(s);
    }
    if(e.getSource() == Num4)
    {
        s += "4";
        display.setText(s);
    }
    if(e.getSource() == Num5)
    {
        s += "5";
        display.setText(s);
    }
    if(e.getSource() == Num6)
    {
        s += "6";
        display.setText(s);
    }
    if(e.getSource() == Num7)
    {
        s += "7";
        display.setText(s);
    }
    if(e.getSource() == Num8)
    {
        s += "8";
        display.setText(s);
    }
    if(e.getSource() == Num9)
    {
        s += "9";
        display.setText(s);
    }
    if(e.getSource() == Num0)
    {
        s += "0";
        display.setText(s);
    }
    if(e.getSource() == Add)
    {
        s += "+";
        display.setText(s);
    }
    if(e.getSource() == Sub)
    {
        s += "-";
        display.setText(s);
    }
    if(e.getSource() == Mult)
    {
        s += "*";
        display.setText(s);
    }
    if(e.getSource() == Div)
    {
        s += "/";
        display.setText(s);
    }
    if(e.getSource() == Eq)
    {
        String result = "" + math.doMath1(s);
        display.setText(result);
    }

}
}

我的计算类(按预期工作,只需要知道如何将我的 GUI 包裹在它上面):

public class doMath
{
Stack stack = new Stack();

String next = "";

public doMath()
{

}

public int doMath1(String expr)
{
    while( expr.length()  >0) //for(int i = 0; i < expr.length(); i++)
{              
    if(expr.length() == 0)
        return 0;
    if(expr.indexOf(" ")>0)
    {
        next = expr.substring(0,expr.indexOf(" "));

        if(next.equals("+"))
            stack.push(stack.pop() + stack.pop());
        else if(next.equals("-"))
        {
            int x = stack.pop();
            stack.push(stack.pop()- x);
        }
        else if(next.equals("*"))
            stack.push(stack.pop() * stack.pop());
        else if(next.equals("/"))
        {
            int x = stack.pop();
            stack.push(stack.pop()/ stack.pop());
        }
        else 
        stack.push(new Integer(Integer.parseInt(next)));         
         expr = expr.substring(expr.indexOf(" ")+1);
    }        
}

    return stack.pop();
}    
}

错误:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI.actionPerformed(GUI.java:126)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at     javax.swing.plaf.basic.BasicButtonListener.
    mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3129)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at         java.awt.EventDispatchThread.pumpOneEventForHierarchy
    (EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy
    (EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)

【问题讨论】:

  • 我会在这里寻找一个关于这种事情的好教程:docs.oracle.com/javase/tutorial/uiswing/events/… 这是一个关于如何编写 actionListeners 的教程
  • 您似乎拥有大量的 JButton。如果这是我,我想为他们使用相同的动作监听器,我会使用数组和 for 循环,而不是重复输入代码。

标签: java swing user-interface wrapper


【解决方案1】:

从您的代码来看,您似乎有一个可行的模型。

基本上,您需要为每个按钮附加一个ActionListener。在你的情况下,我会使用同一个监听器的单个实例......

ActionListener calculatorActionHandler = new CalculatorActionHandler();
Num1.addActionListener(calculatorActionHandler);

在这个处理程序中,我将获取按钮的文本并将它们连接在一起

public class CalculatorActionHandler implements ActionListener {
    private StringBuilder expression = new StringBuilder(32);
    private Gui gui;

    public CalculatorActionHandler(Gui gui) {
        this.gui = gui;
    }

    public void actionPerformed(ActionEvent e) {
        JButton source = (JButton)e.getSource();
        String text = source.getText();
        if (text.equals("=")) {
            doMath math = new doMath();
            int result = math.doMath1(expression.toString());
            expession = new StringBuilder(32);
            // Update the UI
        } else {
            expession.append(text);
            // Update this value to the screen, maybe using a JLabel
        }
    }
}

【讨论】:

  • 尝试更新 UI,但我认为这样做会更容易 import javax.swing.*;导入 java.awt.*;导入 java.awt.event.*;公共类 CalcActionHandler 实现 ActionListener { GUI gui = new GUI(); public void actionPerformed(ActionEvent e) { JButton source = (JButton)e.getSource();字符串文本 = source.getText();字符串 s= ""; if (text.equals("=")) { doMath math = new doMath(); int 结果 = math.doMath1(s);字符串答案=“”+结果; gui.display.setText(answer); } 其他 { s += 文本; gui.display.setText(s); } } }
  • 我不想使用字符串生成器,所以我只是将每个值添加到字符串中,以便我可以将它放在我的文本字段中,但它在我的 gui 中给了我一个插入错误当我尝试编译时,你能帮我解决这个问题吗?
  • 你不应该在动作监听器中创建一个新的GUI,这使它成为对动作监听器的本地引用,并且对你在屏幕上的内容没有任何影响。相反,我可能会在创建动作侦听器时将对GUI 的引用传递给它。此外,每次触发操作事件时,您都会创建一个空白 String,这意味着您不再维护表达式,只保留最后按下的键
  • 你为什么不想使用StringBuilder?它比字符串连接更有效
  • 字符串连接在 Java 中是一项昂贵的操作,对于每个连接,Java 需要创建 n + 1 个字符串对象(这样s += text 最终会创建三个字符串对象)。随着时间的推移,诸如此类的短期对象会对垃圾收集器产生不利影响。虽然通常我们谈论必须在短时间内进行 100 次串联,但如果可以的话,最好避免这样做。
【解决方案2】:

通过实施 ActionListener,您有了一个良好的开端。

你需要添加

addActionListener(this)

致您的每一位JButtons。

然后对于每个按钮,您需要一个 if 语句,或者在这种情况下可能使用 switch 会更好,但它应该如下所示:

String text = "";

....

if(e.getSource() == Num1)
{
    text += "1"
    display.setText(text);
}

/*continue this pattern for the other
  buttons, adding the character to the 
  text string */

对于您的等号按钮,在输入的表达式上调用doMath 方法并将结果写入显示器。

上面的代码可能有错误,你应该参考我在上面评论中发布的链接。

【讨论】:

  • 在我的构造函数中我把 Num1.addActionListner(this); Num2.addActionListener(this);等等......在我的actionperformed中,我为每个按钮添加了if语句。代码可以编译,但是当我单击一个按钮时,我得到一个空指针异常......我将编辑我拥有的代码,并输入我得到的错误
  • 你有没有声明过 String s
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2021-10-23
  • 2014-04-16
相关资源
最近更新 更多