JTextArea не будет отображать предыдущий ввод - PullRequest
0 голосов
/ 11 ноября 2018

В настоящее время я работаю над калькулятором с использованием графического интерфейса.

Вот что я имею в виду и как это должно работать.

  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);
  }
 }
}

Вот так выглядит мой калькулятор.

калькулятор:

https://i.stack.imgur.com/QEmIC.png

Любая помощь в том, как я могу отобразить вывод, как в примере выше.

Спасибо.

Ответы [ 4 ]

0 голосов
/ 12 ноября 2018

Чтобы отобразить текст после операций, как вы указали выше, вы можете сделать это, добавив в метод setText необходимый текст: textArea.setText (display + "+, введенный пользователем \ n") или что-нибудь подобное. Но это не поможет вам получить результат, и вы получите сообщение об ошибке. Зачем? Потому что у вас есть проблема с чтением второй переменной "equalTemp = Double.parseDouble (textArea.getText ())". Фактически этот метод извлекает ВСЕ значения / символы / и т. Д., Отображаемые в textArea, и, таким образом, выдаст сообщение об ошибке, поскольку невозможно преобразовать их все в двойной формат. Чтобы решить эту проблему, вы должны изменить способ сохранения введенных значений. Например, вы можете преобразовать весь текст в textArea в строку, а затем разделить () его определенным символом и после этого сохранить оставшиеся значения как двойные.

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
0 голосов
/ 11 ноября 2018

Вы хотите, чтобы числа входили в одну строку, если они 0-9, верно? Это сделает это. Вместо создания 10 объектов JButton создайте один массив из него и инициализируйте их с помощью цикла, а затем добавьте к ним actionlistener.

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, он становится единым и отображается в текстовой области. Теперь, когда вы нажимаете 2, значение дисплея становится display = display + "2". На этот раз, когда вы передаете переменную отображения в textArea, она не просто теряет значение, потому что она не редактируется напрямую.

Вы можете использовать эту логику, чтобы исправить другие ваши методы. Кроме того, поскольку все значения являются строками, для выполнения вычислений вам необходимо преобразовать строку в целое число. Вы можете использовать Integer.valueOf (дисплей) в этом случае.

Надеюсь, это поможет.

0 голосов
/ 11 ноября 2018
display = textArea.getText();
textArea.setText(display + "3");

Не используйте getText () и setText (). Это не очень эффективно.

Каждый раз, когда вы используете getText (), текстовая область должна анализировать документ для создания строки. Каждый раз, когда вы используете setText (), текстовая область должна анализировать строку для создания документа.

Вместо этого вы просто используете:

textArea.append( "3" );

Еще лучше, не используйте пользовательских слушателей для каждой кнопки. Вы можете поделиться общим слушателем для цифровых кнопок. См .: Как добавить комбинацию клавиш для j-кнопки в java? , например, для начала.

Я хочу, чтобы калькулятор отображал предыдущие входные данные и переходил на новую строку после нажатия математического оператора.

Тогда дополнительный ActionListener (например) будет делать что-то вроде:

textArea.append( "+\n" );

Это необходимо сделать для всех ваших операторов.

0 голосов
/ 11 ноября 2018

Ваш код вернет ваш ответ только из-за оператора присваивания. Попробуйте использовать несколько переменных для хранения ваших значений, затем используйте «\ n», чтобы разбить их там, где вы хотите, чтобы они ломались.

...