Простой калькулятор ( ADD - Sub)

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

введите описание изображения здесь

Вот мой код

   import javax.swing.*;
   import java.awt.*;
   import java.awt.event.*;
    class SimpleMath extends JFrame /*implements ActionListener*/
   { 

   private JLabel label ; //Firstnumber
   private JLabel labe2; // Second number 
   private JLabel labe3; // result 
   private JButton Add;// add 
   private JButton Sub; // subtrack
   private JTextField inputLine1;// enter the firstnumber 
    private JTextField inputLine2;//enter the second number
   private JTextArea  textArea;//the result

   public static void main (String [] args)
   {

   }

   public SimpleMath () {
    Container contentPane = getContentPane( );
         setSize      (300, 300);
         setResizable (false);
         setTitle     ("Simple Math");
         setLocation  (200, 300);
         contentPane.setLayout(null);

         //lebal 1 
         label = new JLabel("First number" ) ; 
         label. setBounds(15 , 30 , 150 , 50 ) ; 
         contentPane.add(label );

         //lebal2
          labe2 = new JLabel("Second number" ) ; 
         label. setBounds(15 , 30 ,1700 , 70 ) ; 
         contentPane.add(label );

         //lebal3
         labe3 = new JLabel("Result" ) ; 
         label. setBounds(15 , 30 ,200 , 100 ) ; 
         contentPane.add(label );


         //text input1 first number
         inputLine1 = new JTextField();
         inputLine1.setColumns(10);
         inputLine1.setFont(new Font("Courier", Font.PLAIN, 14));
         inputLine1. setBounds(15 , 70 , 150 , 25 ) ; 
         contentPane.add(inputLine1 );


         // text input2 second number 
         inputLine2 = new JTextField();
         inputLine2.setColumns(10);
         inputLine2.setFont(new Font("Courier", Font.PLAIN, 14));
         inputLine2. setBounds(15 , 70 , 150 , 25 ) ; 
         contentPane.add(inputLine2 );

         // add button 
         Add= new JButton("search ");
         Add. setBounds(200 , 70 , 220 , 60 ) ; 
         contentPane.add(Add) ;

         // sub button 
         Sub= new JButton("search ");
         Sub. setBounds(200 , 70 , 240 , 60 ) ; 
         contentPane.add(Sub) ;


         //text area that will show the result of the add and sub
         textArea = new JTextArea();
         textArea.setColumns(5);
         textArea.setRows(2);
         textArea.setBorder(BorderFactory.createLineBorder(Color.red));
         textArea.setEditable(false);
         textArea. setBounds(40 , 250 , 300 , 100 ) ; 
         contentPane.add(textArea); 

          return ; }}

3 ответа

Вместо Integer вы можете использовать double, чтобы вы могли получать значения также в десятичном виде.

double First = Double.parseDouble(jTextField1.getText());

// Read the Second number

double Second = Double.parseDouble(jTextField2.getText());

// Set the Result


double Result = First / Second;


    jLabel1.setText(String.valueOf(Result));

Если вы используете Netbeans для разработки графического интерфейса, просто дважды нажмите кнопку "Добавить" и добавьте в нее следующий код

int firstNumber = Integer.parseInt(inputline1.getText());
int secondNumber = Integer.parseInt(inputline2.getText());
int sum = firstNumber + secondNumber;
textArea.setText(Integer.ToString(sum));

Я предлагаю вам прочитать эту тему, чтобы улучшить ваш макет. Использование менеджеров макетов Это очень богатый материал об использовании менеджеров макетов в Swing.

Вы должны создать свой JFrame в своем основном методе. Вот пример:

SimpleMath sm = new SimpleMath();
sm.setVisible(true);

Если вы хотите, чтобы кнопки выполняли какое-то действие, вы должны добавить к нему слушателей действия. Вот пример того, как я бы это сделал:

Add.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        // Read the first number
        int first = Integer.parseInt(inputLine1.getText());
        // Read the second number
        int second = Integer.parseInt(inputLine2.getText());
        // Set the result
        int result = first + second;
        textArea.setText(String.valueOf(result));
    }
});
Другие вопросы по тегам