【问题标题】:JTextArea won't show the previous inputJTextArea 不会显示以前的输入
【发布时间】:2019-04-14 12:50:52
【问题描述】:

我目前正在使用 GUI 开发计算器。

这就是我的意思以及它应该如何工作。

  1. 在输入一系列数字运算符号后,用户可以 点击: ‘=’,在这种情况下,计算器必须显示: i. ‘=’ 第二个数字的最后一个数字后的符号 ii.操作的结果,在一个新的行上 iii。之后输入的任何其他内容 ‘=’ 符号是新计算的一部分,必须显示在 单独一行

例如用户点击:123.45+456.2=1”。屏幕应如下所示:

  • 123.45+ 由用户输入

  • 456.2= 由用户输入

  • 579.65 由您的程序计算并显示

这就是我希望计算器显示先前输入并在单击数学运算符后转到新行的方式。请注意,我也尝试过追加,但没有成功。

代码:

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

public class CalculatorFrame extends JFrame {

 /**
  * All the buttons that will be used in the calculator have been initialized 
  */
 private JButton button1;
 private JButton button2; 
 private JButton button3;
 private JButton button4;
 private JButton button5;
 private JButton button6; 
 private JButton button7;
 private JButton button8;
 private JButton button9;
 private JButton button0; 

 private JButton buttonEqual;
 private JButton buttonDot;

 private JButton buttonClearLast;
 private JButton buttonClearAll;

 private JButton buttonAdd;
 private JButton buttonSub;
 private JButton buttonMul;
 private JButton buttonDiv;

 private JTextArea textArea; 
 private JScrollPane scrollPane;

 private JTextField textFieldResult;

 String display = "";
 private double TEMP;
 private double equalTemp;
 private int clearLastChar = 1;

 Boolean additionBoolean = false;
 Boolean subtractionBoolean = false;
 Boolean multiplicationBoolean = false;
 Boolean divisionBoolean = false;

 public CalculatorFrame(){

  JPanel panel2 = new JPanel();  
  panel2.setLayout(new GridLayout(1,1));
  panel2.add(buttonClearLast = new JButton ("Clear Last"));
  panel2.add(buttonClearAll = new JButton ("Clear All"));
  add(panel2, BorderLayout.PAGE_START);

  JPanel panel3 = new JPanel();
  textArea = new JTextArea();
  scrollPane = new JScrollPane(textArea);
  scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
  add(scrollPane);
  add(panel3, BorderLayout.AFTER_LAST_LINE);  

  JPanel panel1 = new JPanel();
  panel1.setLayout(new GridLayout(4,4));  

  panel1.add(button7 = new JButton ("7"));
  panel1.add(button8 = new JButton ("8"));
  panel1.add(button9 = new JButton ("9"));
  panel1.add(buttonAdd = new JButton ("+"));
  panel1.add(button4 = new JButton ("4"));
  panel1.add(button5 = new JButton ("5"));
  panel1.add(button6 = new JButton ("6"));
  panel1.add(buttonSub = new JButton ("-"));
  panel1.add(button1 = new JButton ("1"));
  panel1.add(button2 = new JButton ("2"));
  panel1.add(button3 = new JButton ("3"));
  panel1.add(buttonMul = new JButton ("*"));
  panel1.add(button0 = new JButton ("0"));
  panel1.add(buttonDot = new JButton ("."));
  panel1.add(buttonEqual = new JButton ("="));
  panel1.add(buttonDiv = new JButton ("/"));  
  add(panel1, BorderLayout.PAGE_END);

  pack();
  buttonClearLast.addActionListener(new ListenToClearLast());
  buttonClearAll.addActionListener(new ListenToClearAll());

  button1.addActionListener(new ListenToOne());
  button2.addActionListener(new ListenToTwo());
  button3.addActionListener(new ListenToThree());
  button4.addActionListener(new ListenToFour());
  button5.addActionListener(new ListenToFive());
  button6.addActionListener(new ListenToSix());
  button7.addActionListener(new ListenToSeven());
  button8.addActionListener(new ListenToEight());
  button9.addActionListener(new ListenToNine());  
  button0.addActionListener(new ListenToZero());

  buttonAdd.addActionListener(new ListenToAdd());
     buttonSub.addActionListener(new ListenToSub());
   buttonMul.addActionListener(new ListenToMul());
   buttonDiv.addActionListener(new ListenToDiv());

   buttonEqual.addActionListener(new ListenToEqual());
   buttonDot.addActionListener(new ListenToDot());

 }

 /**
  * This is where the action listener listens to all the button being pressed
  * Once heard, it will show case it to the TextArea of the calculator. 
  */

 public class ListenToOne implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("1");
  }
 }

 public class ListenToTwo implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("2");
  }
 }

 public class ListenToThree implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("3");
  }
 }

 public class ListenToFour implements ActionListener{
  public void actionPerformed(ActionEvent e){
 //  display = textArea.getText();
   textArea.append("4");
  }
 }

 public class ListenToFive implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("5");
  }
 }

 public class ListenToSix implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("6");
  }
 }

 public class ListenToSeven implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("7");
  }
 }

 public class ListenToEight implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("8");
  }
 }

 public class ListenToNine implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("9");
  }
 }

 public class ListenToZero implements ActionListener{
  public void actionPerformed(ActionEvent e){
//   display = textArea.getText();
   textArea.append("0");
  }
 }

 // This is used for decimal points. 
 // If the dot button is clicked, it will display "." 
 public class ListenToDot implements ActionListener{
  public void actionPerformed(ActionEvent e){
 //  display = textArea.getText();
   textArea.append(".");
  }
 }

 // The next 4 methods are for the basic operators. 
 // If any of the operator button is clicked, it would set it's boolean value to true and 
 // tell the program which operation to perform 

 public class ListenToAdd implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.append("+\n");
   additionBoolean = true;
  }
 }

 public class ListenToSub implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.setText("- \n");
   subtractionBoolean = true;
  }
 }

 public class ListenToMul implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.setText("* \n");
   multiplicationBoolean = true;
  }
 }

 public class ListenToDiv implements ActionListener{
  public void actionPerformed (ActionEvent e){
   TEMP = Double.parseDouble(textArea.getText());
   textArea.setText("/ \n");
   divisionBoolean = true;
  }
 }

 // This ListenToEqual method does all the calculation
 // First, the program is checking what kind of calculation to perform by comparing it's boolean values. 
 // Once that is done, it will get the previous input from the user using the getText method and add/sub/mul/div with the new value 
 // The output will be displayed in the text area. 

 public class ListenToEqual implements ActionListener{
  public void actionPerformed (ActionEvent e){

   equalTemp = Double.parseDouble(textArea.getText());
   if (additionBoolean == true)
    equalTemp = equalTemp + TEMP;
   else if (subtractionBoolean == true)
    equalTemp = TEMP - equalTemp;
   else if (multiplicationBoolean == true)
    equalTemp = equalTemp * TEMP;
   else if (divisionBoolean == true)
    equalTemp = TEMP / equalTemp;

   textArea.append(Double.toString(equalTemp)); 
  // textArea.setText("1");

   additionBoolean = false;
   subtractionBoolean = false;
   multiplicationBoolean = false;
   divisionBoolean = false;
  }
 }

 public class ListenToClearAll implements ActionListener{
  public void actionPerformed (ActionEvent e){
   textArea.setText("");
   additionBoolean = false;
   subtractionBoolean = false;
   multiplicationBoolean = false;
   divisionBoolean = false;
   TEMP = 0;
   equalTemp = 0;
  }
 }

 public class ListenToClearLast implements ActionListener{
  public void actionPerformed (ActionEvent e){
   String currentChar = textArea.getText();
   String currentCharMinus = currentChar.substring(0,currentChar.length()-clearLastChar);
   textArea.setText(currentCharMinus);
  }
 }
}

这就是我的计算器的外观。

计算器:

关于如何显示上面示例中的输出的任何帮助。

谢谢。

【问题讨论】:

    标签: java user-interface append jtextarea


    【解决方案1】:

    要在上述操作后显示文本,您可以通过向 setText 方法添加必要的文本来实现:textArea.setText(display + "+ enter by user\n") 或类似的任何内容。但它不会帮助您获得结果,并且您会收到一条错误消息。为什么?因为您在读取第二个变量“equalTemp = Double.parseDouble(textArea.getText())”时遇到问题。事实上,此方法会取出 textArea 中显示的所有值/字符/等,因此会给您一条错误消息,因为无法将它们全部转换为 Double 格式。要解决此问题,您必须更改输入值的保存方式。例如,您可以将 textArea 中的所有文本转换为字符串,然后使用特定符号将其拆分(),然后将剩余的值保存为 Double 值。

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.util.regex.PatternSyntaxException;
    
    class CalculatorFrame extends JFrame {
    
    /**
     * All the buttons that will be used in the calculator have been initialized 
     */
    private JButton button1;
    private JButton button2; 
    private JButton button3;
    private JButton button4;
    private JButton button5;
    private JButton button6; 
    private JButton button7;
    private JButton button8;
    private JButton button9;
    private JButton button0; 
    
    private JButton buttonEqual;
    private JButton buttonDot;
    
    private JButton buttonClearLast;
    private JButton buttonClearAll;
    
    private JButton buttonAdd;
    private JButton buttonSub;
    private JButton buttonMul;
    private JButton buttonDiv;
    
    private JTextArea textArea; 
    private JScrollPane scrollPane;
    
    String display = "";
    String[] arr;
    private double result;
    
    Boolean additionBoolean = false;
    Boolean subtractionBoolean = false;
    Boolean multiplicationBoolean = false;
    Boolean divisionBoolean = false;
    Boolean equals = false;
    
    public CalculatorFrame(){
    
        JPanel panel2 = new JPanel();       
        panel2.setLayout(new GridLayout(1,1));
        panel2.add(buttonClearLast = new JButton ("Clear Last"));
        panel2.add(buttonClearAll = new JButton ("Clear All"));
        add(panel2, BorderLayout.PAGE_START);
    
        JPanel panel3 = new JPanel();
        textArea = new JTextArea(10, 20);
        scrollPane = new JScrollPane(textArea);
    
    scrollPane.setVerticalScrollBarPolicy(
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        add(scrollPane);
        add(panel3, BorderLayout.AFTER_LAST_LINE);      
    
        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayout(4,4));      
    
    
        panel1.add(button7 = new JButton ("7"));
        panel1.add(button8 = new JButton ("8"));
        panel1.add(button9 = new JButton ("9"));
        panel1.add(buttonAdd = new JButton ("+"));
        panel1.add(button4 = new JButton ("4"));
        panel1.add(button5 = new JButton ("5"));
        panel1.add(button6 = new JButton ("6"));
        panel1.add(buttonSub = new JButton ("-"));
        panel1.add(button1 = new JButton ("1"));
        panel1.add(button2 = new JButton ("2"));
        panel1.add(button3 = new JButton ("3"));
        panel1.add(buttonMul = new JButton ("*"));
        panel1.add(button0 = new JButton ("0"));
        panel1.add(buttonDot = new JButton ("."));
        panel1.add(buttonEqual = new JButton ("="));
        panel1.add(buttonDiv = new JButton ("/"));  
        add(panel1, BorderLayout.PAGE_END);
    
    
        pack();
    //  buttonClearLast.addActionListener(new ListenToClearLast());
        buttonClearAll.addActionListener(new ListenToClearAll());
    
        button1.addActionListener(e -> {textArea.setText(display() + "1");});
        button2.addActionListener(e -> {textArea.setText(display() + "2");});
        button3.addActionListener(e -> {textArea.setText(display() + "3");});
        button4.addActionListener(e -> {textArea.setText(display() + "4");});
        button5.addActionListener(e -> {textArea.setText(display() + "5");});
        button6.addActionListener(e -> {textArea.setText(display() + "6");});
        button7.addActionListener(e -> {textArea.setText(display() + "7");});
        button8.addActionListener(e -> {textArea.setText(display() + "8");});
        button9.addActionListener(e -> {textArea.setText(display() + "9");});      
        button0.addActionListener(e -> {textArea.setText(display() + "0");});
    
        buttonAdd.addActionListener(e -> {textArea.setText(display() + "+ enterd by user\n"); additionBoolean = true;});
        buttonSub.addActionListener(e -> {textArea.setText(display() + "- enterd by user\n"); subtractionBoolean = true;});
        buttonMul.addActionListener(e -> {textArea.setText(display() + "* enterd by user\n"); multiplicationBoolean = true;});
        buttonDiv.addActionListener(e -> {textArea.setText(display() + "/ enterd by user\n"); divisionBoolean = true;});
        buttonDot.addActionListener(e -> {textArea.setText(display() + ".");});
    
        buttonEqual.addActionListener(e -> {calculation();
                                            textArea.setText(display() + "= enterd by user\n" + result + " this is your result");
                                            });
       }
    
    private String display() {
        display = textArea.getText();
        return display;
        }
    
    private void calculation() {
        String str = display();
    
        if (additionBoolean == true) {
            arr = str.split("\\+ enterd by user");
            result = Double.parseDouble(arr[0]) + Double.parseDouble(arr[1]);
            }
        else if (subtractionBoolean == true) {
            arr = str.split("- enterd by user");
            result = Double.parseDouble(arr[0]) - Double.parseDouble(arr[1]);
            }
        else if (multiplicationBoolean == true) {
            arr = str.split("\\* enterd by user");
            result = Double.parseDouble(arr[0]) * Double.parseDouble(arr[1]);
            }
        else if (divisionBoolean == true) {
            arr = str.split("/ enterd by user");
            result = Double.parseDouble(arr[0]) / Double.parseDouble(arr[1]);
            }
    }
    /**
     * This is where the action listener listens to all the button being pressed
     * Once heard, it will show case it to the TextArea of the calculator. 
     */
    
    public class ListenToClearAll implements ActionListener{
        public void actionPerformed (ActionEvent e){
            textArea.setText("");
            additionBoolean = false;
            subtractionBoolean = false;
            multiplicationBoolean = false;
            divisionBoolean = false;
        }
    }
    } 
    

    例如,您将得到 9.25 和 23.7 之和的下一个结果:

    9.25+ enterd by user
    23.7= enterd by user
    32.95 this is your result
    

    【讨论】:

      【解决方案2】:
      display = textArea.getText();
      textArea.setText(display + "3");
      

      不要使用 getText() 和 setText()。它不是很有效。

      每次使用 getText() 时,文本区域都需要解析 Document 以创建一个字符串。每次使用 setText() 时,文本区域都需要解析字符串来创建文档。

      您只需使用:

      textArea.append( "3" );
      

      更好的是,不要为每个按钮使用自定义侦听器。您可以为数字按钮共享一个通用侦听器。请参阅:How to add a shortcut key for a jbutton in java? 获取入门示例。

      我希望计算器显示以前的输入,并在单击数学运算符后转到新行。

      然后,附加的 ActionListener(例如)将执行以下操作:

      textArea.append( "+\n" );
      

      您需要为所有运营商这样做。

      【讨论】:

      • 好的,添加您提到的内容后,我能够满足大部分要求。现在,当我尝试在数字末尾显示减法、乘法和除法时,它会用“选择的运算符”替换整个输入,而不执行任何计算。检查代码。
      • it would replace the whole input with a "chosen operator" - 我不知道那是什么意思。使用 append() 方法没有什么秘密。它会准确地追加你告诉它追加的内容。因此,如果您没有看到正确的符号,那么您需要进行一些基本的调试。您是否使用调试器单步执行代码以查看逻辑流程?您是否将 System.out.println(...) 语句添加到每个 ActionListner 以查看它是否正在执行。这些是您需要执行的基本调试步骤。
      • it would replace the whole input with a "chosen operator" - 使用 append() 方法没有秘密。它会准确地追加你告诉它追加的内容。如果您只看到要附加的运算符,那么这意味着您在代码中的某处使用的是 setText() 而不是 append() 方法。你需要做一些基本的调试。您是否使用调试器单步执行代码以查看逻辑流程?您是否将 System.out.println(...) 语句添加到每个 ActionListener 以查看它是否正在执行。这些是您需要执行的基本调试步骤。
      • 您是对所有运算符使用 append() 还是只对“+”运算符使用?既然你有了答案,别忘了“接受”一个答案,这样人们就知道问题已经解决了。
      【解决方案3】:

      只要数字是 0-9,您希望数字进入同一行,对吗?这会做到的。与其创建 10 个 JButton 对象,不如创建一个数组并使用循环初始化它们,并相应地为它们添加一个动作监听器。

      private JButton[] buttons;
      
      buttons = new JButton[10];
      
      for(int i = 0; i < buttons.length; i++) {
              // Make all the buttons and add them to the panel
              panel1.add(buttons[i] = new JButton(String.valueOf(i)));
              // Add an actionlistener to each of them
              buttons[i].addActionListener(this);
          }
      

      下面是您如何为这些按钮使用 actionListener 接口(确保一开始就在您的 CalculatorFrame 类中实现它):

      @Override
      public void actionPerformed(ActionEvent e) {
          for(int i = 0; i < buttons.length; i++) {
              // Check if the button pressed was a button0 - button 9
              if(e.getSource() == buttons[i]) {
                  // whichever button (0-9) was pressed, append its result into display string
                  display += String.valueOf(i);
              }
          }
          // Now set the result into your text area
          textArea.setText(display);
      }
      

      现在每次按下按钮时,它都会在同一行而不是新的,因为您不是直接更改 textArea 的值,而是将一个字符串放入其中,该字符串每次都会附加你按下一个按钮。

      所以最初,显示变量的值是什么。当你按下 1 时,它变为 1 并显示在 textArea 中。现在,当您按 2 时,显示的值变为 display = display + "2"。这一次,当您将显示变量传递给 textArea 时,它不仅会丢失值,因为它没有被直接编辑。

      您可以使用此逻辑来修复您的其他方法。此外,由于所有值都是字符串,因此要执行计算,您需要将字符串转换为整数。你可以使用 Integer.valueOf(display) 是这种情况。

      希望这会有所帮助。

      【讨论】:

        【解决方案4】:

        由于赋值运算符,您的代码只会返回您的答案。尝试使用多个变量来存储您的值,然后使用“\n”在您希望它们中断的位置进行中断。

        【讨论】:

        • 嘿,正如你所说,我已经使用 \n 跳过该行。但是我将如何跟踪以前的输入并将其与运算符一起显示到文本区域
        • int var1。当您单击任何运算符时,您将文本区域上的值分配给您的变量,然后再计算以获得结果。
        猜你喜欢
        • 2012-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-12
        • 2017-02-12
        • 2019-02-05
        • 2012-05-27
        相关资源
        最近更新 更多