Search code examples
javaswinguser-interfacecalculatorjcombobox

Using JComobBox, find results of 2 numbers and output to the results (Java)


I am to make a simple calculator but I am having issues with this:

When the button is pressed it should do the following:

  • Get the text from the two JTextFields and convert them to Doubles. Use Double.parseDouble(String input) to turn a String into a Double. (Not sure where to put this?)
  • Get the text from the JComboBox. Use the getSelectedItem() method to get the currently selected string. (Not sure if I did this correctly)
  • Calculate the result based on the string from the JComboBox This determines if you will use the + operator, - operator, * operator or / operator. (do not know how to do this)
  • Set the result to the JLabel Use the .setText() method to construct a String

These are my 4 problems.

class MyFrame extends JFrame {

public JTextField firstNumber;
public JTextField secondNumber;
public JButton calc;
public JLabel result;
public JComboBox combo;

public MyFrame() {
    super();
    init();
}

private void init() {
    
    JButton calc = new JButton("Calculate");
    calc.addActionListener(new MyButtonListener(this));
    firstNumber = new JTextField();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.add(calc);
    this.add(firstNumber);
    this.add(secondNumber);
    this.pack();
    this.setVisible(true);
}
}

class MyButtonListener implements ActionListener {
MyFrame fr;

public MyButtonListener(MyFrame frame)
{
    fr = frame;
    fr.firstNumber.getText();
    fr.secondNumber.getText();
    fr.combo.getSelectedItem();
}


public void actionPerformed(ActionEvent e) 
{
    JButton btn = (JButton) e.getSource();
    
}
}

private static void constructGUI() {

JFrame.setDefaultLookAndFeelDecorated(true);

JTextField firstNumber = new JTextField();
JTextField secondNumber = new JTextField();
JButton calc = new JButton("Calculate"); 
JLabel result = new JLabel();
JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Simple Calculator");


 String[] arth = { "Add", "Subtract", "Multiple", 
 "Divide" };
 JComboBox combo = new JComboBox(arth);
 combo.setSelectedIndex(0);

frame.setLayout(new GridLayout(5, 2));
frame.add(new JLabel("First Number:"));
frame.add(firstNumber);
frame.add(new JLabel("Second Number:"));
frame.add(secondNumber);
frame.add(combo);
frame.add(calc);
frame.add(new JLabel("Result:"));
frame.pack();
frame.setSize(200, 200);
frame.setVisible(true);
}   


public static void main(String[] args) 
{
SwingUtilities.invokeLater(new Runnable() 
{
    public void run() 
    {
        constructGUI();
    }   
});
}
}

Solution

  • Your MyFrame is not connected with the rest of the code invoked in main.

    1. Added listener to your result field (also included in JFrame because it was not used) - code from lambda can be extracted for better visibility

    2. Added only "ADD" rest will be similar

      private static void constructGUI() {

      JFrame.setDefaultLookAndFeelDecorated(true);
      
      JTextField firstNumber = new JTextField();
      JTextField secondNumber = new JTextField();
      JButton calc = new JButton("Calculate");
      JLabel result = new JLabel("Result:");
      JFrame frame = new JFrame();
      
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setTitle("Simple Calculator");
      
      String[] arth = {"Add", "Subtract", "Multiple", "Divide"};
      JComboBox combo = new JComboBox(arth);
      combo.setSelectedIndex(0);
      
      frame.setLayout(new GridLayout(5, 2));
      frame.add(new JLabel("First Number:"));
      frame.add(firstNumber);
      frame.add(new JLabel("Second Number:"));
      frame.add(secondNumber);
      frame.add(combo);
      frame.add(calc);
      frame.add(result);
      frame.pack();
      frame.setSize(200, 200);
      frame.setVisible(true);
      
      calc.addActionListener(
          e -> {
            var first = Double.parseDouble(firstNumber.getText());
            var secound = Double.parseDouble(secondNumber.getText());
            double res = 0;
      
            switch (Objects.requireNonNull(combo.getSelectedItem()).toString()) {
              case "Add":
                res = first + secound;
                break;
            }
            result.setText(String.valueOf(res));
          });
      

      }

    Simplified main:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(Main2::constructGUI);
      }