有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在另一个文本框中输入操作后在JLabel中显示输出?

我现在正在做一个计算器,我在一个文本框中输入操作,右边有一个按钮。如果我在文本框中按enter键或按下按钮,答案或错误消息应显示在下方的JLabel中。我能够在某种程度上显示输入文本框和按钮,但不知道在单击按钮或按下标签中的enter键后如何显示答案

观众

import javax.swing.JFrame;

public class CalculatorViewer {

    public static void main(String[] args) {
        JFrame frame = new CalculatorViewerFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("FontViewer");
        frame.setVisible(true);
    }

}

框架

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

public class CalculatorViewerFrame extends JFrame {
       private JLabel resultLabel;
       private JTextField inputField;
       private JButton button;
       private ActionListener listener;

       private static final int FRAME_WIDTH = 500;
       private static final int FRAME_HEIGHT = 300;

       public CalculatorViewerFrame() {
           class Calculate implements ActionListener {
               public void actionPerformed(ActionEvent event) {
                   String input = inputField.getText();
                   input = input.trim();
                   int x = 0,y=0;
                   String operator;
                   try {
                       x = Integer.parseInt(input.substring(0,input.indexOf(" ")));
                   } catch(InvalidExpressionException exception) {
                          resultLabel.setText("The first operand is not an integer");
                   }
                   if (input.indexOf(" ")==input.lastIndexOf(" ") || input.indexOf(" ")+1==input.lastIndexOf(" ")) {
                       operator = " ";
                   } else {
                       operator = input.substring(input.indexOf(" "), input.lastIndexOf(" "));
                   }
                   operator = operator.trim();
                   try {
                       y= Integer.parseInt(input.substring(input.lastIndexOf(" ")));
                   } catch(InvalidExpressionException exception) {
                       resultLabel.setText("The second operand is not an integer");
                   }
                   int answer;
                   String operation = x +" " + operator + y+ " = ";
                   switch (operator) {
                    case "+": answer = x + y;
                    resultLabel.setText(operation + answer);
                    resultLabel.repaint();
                    case "-": answer = x - y;
                    resultLabel.setText(operation + answer);
                    resultLabel.repaint();
                    case "*": answer = x * y;
                    switch (y) {
                    case 0: resultLabel.setText("Cannot divide by 0");
                    }
                    resultLabel.setText(operation + answer);
                    resultLabel.repaint();
                    case "/": answer = x / y;
                    resultLabel.setText(operation + answer);
                    resultLabel.repaint();
                    case "%": answer = x % y;
                    resultLabel.setText(operation + answer);
                    resultLabel.repaint();
                    default: resultLabel.setText("Illegal operator");
                   }
               }
           }

           createInputPanel();
           resultLabel = new JLabel();
           add(resultLabel, BorderLayout.CENTER);
           listener = new Calculate();

           setSize(FRAME_WIDTH, FRAME_HEIGHT);
       }


       public void createInputPanel() {
           JPanel inputPanel = createInputTextField();
           JPanel compute = createButton();

           JPanel controlPanel = new JPanel();
           controlPanel.setLayout(new GridLayout(1,2));
           controlPanel.add(inputPanel);
           controlPanel.add(compute);

           add(controlPanel, BorderLayout.NORTH);
       }

       private JPanel createInputTextField() {
           inputField = new JTextField(20);
           inputField.setEditable(true);
           inputField.requestFocus();
           inputField.setText("");
           JPanel panel = new JPanel();
           inputField.addActionListener(listener);
           panel.add(inputField);
           return panel;
       }

       public JPanel createButton() {
           button = new JButton("Compute");
           JPanel panel = new JPanel();
           button.addActionListener(listener);
           panel.add(button);
           return panel;
       }
}

下面是它应该是什么样子/类似的图片。 enter image description here enter image description here enter image description here

非常感谢您的帮助!多谢各位


共 (2) 个答案

  1. # 1 楼答案

    首先:在询问有关StackOverflow的问题之前,请清理您的代码。这有两个主要原因:

    • 更干净的代码更容易被您自己理解。在大多数情况下,在解决问题后,问题是显而易见的,你甚至不必问
    • 第二:每个阅读你的问题的人都必须这样做才能理解它。现在你有20个人可能试图帮助你,他们每个人都必须这样做。这个比例很差

    现在谈谈你的问题:既然你没有写下它是什么,你就有麻烦了,我猜你没有得到按钮按下事件

    原因是,您在创建字段/面板之后实例化了listener = new Calculator()。但是您可以在这里创建它们:inputField.addActionListener(listener);,其中listener仍然是null。所以试着把它移到最上面几行,你就能得到你的比赛

    (如果代码更干净,这是显而易见的,我提到过吗?)

    这段代码中有更多的问题,但是通过这一更改,当单击按钮时,您至少会收到一些错误消息,因此我将留给您

  2. # 2 楼答案

    我非常同意谢因托德的反馈。我会让他自己解决的。我设法优化了你的代码。在代码中查看我的注释并从中学习。我想这是你的家庭作业/项目,是吗?哈哈

    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class CalculatorViewerFrame extends JFrame implements ActionListener { // you dont need to create sub class and
                                                                                    // implement ActionListener to it. You
                                                                                    // can do it here
        private JLabel resultLabel;
        private JTextField inputField;
        private JButton button;
    
        private static final int FRAME_WIDTH = 500;
        private static final int FRAME_HEIGHT = 300;
    
        public CalculatorViewerFrame() {
            createInputPanel();
            resultLabel = new JLabel();
            add(resultLabel, BorderLayout.CENTER);
    
            setSize(FRAME_WIDTH, FRAME_HEIGHT);
        }
    
        private void createInputPanel() { // set your modifier into private, it is not used from other class
            JPanel inputPanel = createInputTextField();
            JPanel compute = createButton();
    
            JPanel controlPanel = new JPanel();
            controlPanel.setLayout(new GridLayout(1, 2));
            controlPanel.add(inputPanel);
            controlPanel.add(compute);
    
            add(controlPanel, BorderLayout.NORTH);
        }
    
        private JPanel createInputTextField() {
            inputField = new JTextField(20);
            inputField.setEditable(true);
            inputField.requestFocus();
            inputField.setText("");
            JPanel panel = new JPanel();
            inputField.addActionListener(this); // since you implemented it to this class. you can use `this` as your input in parameter addActionListener
            panel.add(inputField);
            return panel;
        }
    
        private JPanel createButton() { // set your modifier into private, it is not used from other class
            button = new JButton("Compute");
            JPanel panel = new JPanel();
            button.addActionListener(this); // same thing with line 50
            panel.add(button);
            return panel;
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("Compute")) { // though you have only one action. always check for this as it
                                                            // tells what action event happened.
                // parse and validate
                String input = inputField.getText();
                input = input.trim();
                int x = 0, y = 0;
                String operator;
    
                try {
                    x = Integer.parseInt(input.substring(0, input.indexOf(" ")).trim());
                } catch (NumberFormatException exception) { // check your catch exception too. Remove that is/are not relevant to your try block
                    resultLabel.setText("The first operand is not an integer");
                    return; // you need to stop the process from here. you are using resultLabel all the time and you setText into it.
                }
    
                if (input.indexOf(" ") == input.lastIndexOf(" ") || input.indexOf(" ") + 1 == input.lastIndexOf(" ")) {
                    operator = " ";
                } else {
                    operator = input.substring(input.indexOf(" "), input.lastIndexOf(" "));
                }
                operator = operator.trim();
    
                try {
                    y = Integer.parseInt(input.substring(input.lastIndexOf(" ")).trim()); // trim for white spaces.
                } catch (NumberFormatException exception) {
                    resultLabel.setText("The second operand is not an integer");
                    return; // you need to stop the process from here. you are using resultLabel all the time and you setText into it.
                }
    
                compute(x, y, operator);
            }
        }
    
        private void compute(int x, int y, String operator) { // you can move this block of code into another method as it
                                                                // is a new process.
            int answer;
            String operation = x + " " + operator + y + " = ";
            switch (operator) {
            case "+":
                answer = x + y;
                resultLabel.setText(operation + answer);
                resultLabel.repaint();
                break; // use break as it the process will continue. your case would be useless then.
            case "-":
                answer = x - y;
                resultLabel.setText(operation + answer);
                resultLabel.repaint();
                break;
            case "*":
                answer = x * y; // you dont need to spam switch condition. 
                                // if you are checking for one condition, use IF
                if (y == 0) {
                    resultLabel.setText("Cannot divide by 0");
                }
                resultLabel.setText(operation + answer);
                resultLabel.repaint();
                break;
            case "/":
                answer = x / y;
                resultLabel.setText(operation + answer);
                resultLabel.repaint();
                break;
            case "%":
                answer = x % y;
                resultLabel.setText(operation + answer);
                resultLabel.repaint();
                break;
            default:
                resultLabel.setText("Illegal operator");
                break;
            }
        }
    }
    

    回答您的问题,如何显示输出。您需要在ActionExecuted方法中使用return,当它落在catch块中时。因为你需要终止这个过程

    试着看看这个。 出现错误时,将文本设置为resultLabel。表示“操作数不是整数”

    然后继续计算,并在resultLabel中再次设置文本。resultLabel中的值是多少

    干杯