Home > Enterprise >  Save 3 event in Java Swing Calculator
Save 3 event in Java Swing Calculator

Time:01-14

I'm new and student in Java. Our professor is asking us to create a calculator using keypress.

Here are the instructions:
Run the program. The user can only input numbers using KEYBOARD. After entering the first number, you can only use the 4 BUTTONS to select the desired operation. After pressing the button, you can enter the second number. Press the SOLVE button to display into the textfield the answer.

screen capture

My problem is how can I save the two other command to use it for solving.

Example for num1 I used 5 then (operator and then num2). How can I save them to use in solve button. It confuses me since only one text box is there. I try two text boxes with below codes. It is working but for one box failed to do so.

int a = Integer.parseInt(textFirst.getText());
int b = Integer.parseInt(textSecond.getText());
int c = 0;
if (e.getSource().equals(btnMulti)) {
c = a * b;
textResult.setText(String.valueOf("The product of " a " * " b " is " c));
}

So far, here's my code;

package first_Lab_2022;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class Lab3_2 {

    private JFrame frame;
    private JTextField textField;
    
    int num1,num2 = 0;
    String operator="";

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Lab3_2 window = new Lab3_2();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public Lab3_2() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.getContentPane().addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                
            }
        });
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        textField = new JTextField();
        textField.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                num1 = Integer.parseInt(textField.getText());
            }
        });
        textField.setHorizontalAlignment(SwingConstants.RIGHT);
        textField.setBounds(114, 73, 242, 60);
        frame.getContentPane().add(textField);
        textField.setColumns(10);
        
        JButton btnAdd = new JButton("Add");
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText(String.valueOf(" "));
            }
        });
        
        btnAdd.setBounds(124, 144, 100, 23);
        frame.getContentPane().add(btnAdd);
        
        JButton btnSub = new JButton("Subtract");
        btnSub.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            textField.setText(String.valueOf("-"));
            
            }
        });
        btnSub.setBounds(267, 144, 89, 23);
        frame.getContentPane().add(btnSub);
        
        JButton btnMul = new JButton("Multiply");
        btnMul.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    textField.setText(String.valueOf("*"));
            }
        });
        btnMul.setBounds(124, 190, 100, 23);
        frame.getContentPane().add(btnMul);
        
        JButton btnDiv = new JButton("Divide");
        btnDiv.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText(String.valueOf("/"));
            }
        });
        btnDiv.setBounds(267, 190, 100, 23);
        frame.getContentPane().add(btnDiv);
        
        JButton btnSolve = new JButton("Solve");
        btnSolve.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

//              String a = textField.getText();
//              int i=Integer.parseInt(a);

            }
        });
        btnSolve.setBounds(202, 227, 100, 23);
        frame.getContentPane().add(btnSolve);
    }
}

I do hope someone help me out in this.

CodePudding user response:

There's bit of a danger asking this kind of question here, as you're likely to get a answer which is beyond the scope of your needs and/or understanding.

I suspect that maybe you can make use of JOptionPane to prompt the user for the first number, operator and last number, assigning the results of each request to a variable.

You should start by looking at How to Make Dialogs

For limiting the input to a numeric value, you could make use of a How to Use Formatted Text Fields or a DocumentFilter. Neither is simple. Alternatively, you could use Integer.parse(String) to parse the text returned when prompting the user and put it inside a loop until you get an appropriate response.

For the operators, I'd simply use a JComboBox so as to limit the users input to what you want. See How to Use Combo Boxes.

Now, before you ask, no, I can't give you an example (in fact I've listed a number above). The point of the exercise is for you to apply what you've been taught.

Update based on improved requirements

You're going to be sorry you asked.

The basic concept is you're running in an event driven environment, that is, something happens and you respond to it. It's you're responsibility to manage the state and based on the available information, do things.

As to the requirement to only accept an integer, you could use a DocumentFilter, but this is rather advanced concept, see Implementing a Document Filter for more details. Alternatively, you could just parse the text and present an error message to the user when it fails, that's up to you.

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        enum Operator {
            ADD, SUBTRACT, MULTIPLE, DIVIDE;
        }

        private JTextField inputField;
        private JToggleButton addButton = new JToggleButton("Add");
        private JToggleButton subtractButton = new JToggleButton("Subtract");
        private JToggleButton multipleButton = new JToggleButton("Multiple");
        private JToggleButton divideButton = new JToggleButton("Divide");

        private JButton solveButton = new JButton("Solve");

        private JToggleButton[] operators = new JToggleButton[]{
            addButton, subtractButton, multipleButton, divideButton
        };

        private Integer firstValue;
        private Integer secondValue;
        private Operator operator;

        private ButtonGroup operatorButtonGroup = new ButtonGroup();

        public TestPane() {
            setBorder(new EmptyBorder(32, 32, 32, 32));
            setLayout(new GridBagLayout());

            inputField = new JTextField(10);
            inputField.setHorizontalAlignment(JTextField.TRAILING);
            ((AbstractDocument) inputField.getDocument()).setDocumentFilter(new IntegerDocumentFilter());
            inputField.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void insertUpdate(DocumentEvent e) {
                    updateState();
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    updateState();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    updateState();
                }
            });

            operatorButtonGroup.add(addButton);
            operatorButtonGroup.add(subtractButton);
            operatorButtonGroup.add(multipleButton);
            operatorButtonGroup.add(divideButton);

            addButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    firstValue = getCurrentValue();
                    if (firstValue != null) {
                        setOperator(Operator.ADD);
                        inputField.setText(null);
                    }
                }
            });

            subtractButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    firstValue = getCurrentValue();
                    if (firstValue != null) {
                        setOperator(Operator.SUBTRACT);
                        inputField.setText(null);
                    }
                }
            });

            multipleButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    firstValue = getCurrentValue();
                    if (firstValue != null) {
                        setOperator(Operator.MULTIPLE);
                        inputField.setText(null);
                    }
                }
            });

            divideButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    firstValue = getCurrentValue();
                    if (firstValue != null) {
                        setOperator(Operator.DIVIDE);
                        inputField.setText(null);
                    }
                }
            });

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.anchor = GridBagConstraints.LINE_END;
            add(inputField, gbc);

            JPanel operatorPane = new JPanel(new GridLayout(2, 2));
            operatorPane.add(addButton);
            operatorPane.add(subtractButton);
            operatorPane.add(multipleButton);
            operatorPane.add(divideButton);

            gbc.gridy  ;
            gbc.weightx = 0;
            gbc.anchor = GridBagConstraints.LINE_END;

            add(operatorPane, gbc);

            gbc.gridy  ;
            gbc.weightx = 0;
            gbc.anchor = GridBagConstraints.LINE_END;

            add(solveButton, gbc);

            solveButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Integer secondValue = getCurrentValue();
                    if (firstValue != null && secondValue != null && operator != null) {
                        // Insert your logic here

                        resetState();
                    } else {
                        JOptionPane.showMessageDialog(TestPane.this, "Can't not solve equation, missing required parameters", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });

            solveButton.setEnabled(false);
            setOperatorsEnabled(false);
        }

        protected void resetState() {
            firstValue = null;
            operator = null;

            inputField.setText(null);
            operatorButtonGroup.clearSelection();

            updateState();
        }

        protected Integer getCurrentValue() {
            try {
                return Integer.parseInt(inputField.getText());
            } catch (NumberFormatException exp) {
                return null;
            }
        }

        protected void setOperatorsEnabled(boolean enabled) {
            for (JToggleButton btn : operators) {
                btn.setEnabled(enabled);
            }
        }

        protected void updateState() {
            String currentValue = inputField.getText();
            if (currentValue.isBlank()) {
                solveButton.setEnabled(false);
                setOperatorsEnabled(false);
            } else {
                if (operator != null) {
                    solveButton.setEnabled(true);
                    setOperatorsEnabled(false);
                } else {
                    solveButton.setEnabled(false);
                    setOperatorsEnabled(true);
                }
            }
        }

        protected void setOperator(Operator operator) {
            this.operator = operator;
            updateState();
        }

    }

    public class IntegerDocumentFilter extends DocumentFilter {

        public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
            try {
                int parseInt = Integer.parseInt(text);
                super.insertString(fb, offset, text, attr);
            } catch (NumberFormatException exp) {
                Toolkit.getDefaultToolkit().beep();
            }
        }

        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String string, AttributeSet attr) throws BadLocationException {
            if (string == null || string.isBlank()) {
                super.replace(fb, offset, length, "", attr);
            } else {
                try {
                    int parseInt = Integer.parseInt(string);
                    super.replace(fb, offset, length, string, attr);
                } catch (NumberFormatException exp) {
                    Toolkit.getDefaultToolkit().beep();
                }
            }
        }
    }
}
  •  Tags:  
  • Related