Here's the code:
import javax.swing.JFrame; public class calc { public static void main(String args[]) { JFrame frame = new JFrame("4 Function Calculator"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); calcpanel panel = new calcpanel(); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); } }
import javax.swing.*; import java.awt.event.*; import java.awt.*; public class calcpanel extends JPanel{ private JLabel firstInput, secondInput, outputLabel, resultLabel; private JButton add, sub, mult, div; private JTextField input1, input2; public calcpanel(){ firstInput = new JLabel("Enter a number: "); secondInput = new JLabel("Enter a number: "); outputLabel = new JLabel("Answer: "); resultLabel = new JLabel("---"); add = new JButton("+"); add.addActionListener(new AddListener()); sub = new JButton("-"); sub.addActionListener(new SubListener()); mult = new JButton("x"); mult.addActionListener(new MultListener()); div = new JButton("/"); div.addActionListener(new DivListener()); input1 = new JTextField(5); input2 = new JTextField(5); add (firstInput); add (input1); add (secondInput); add (input2); add (add); add (sub); add (mult); add (div); add (outputLabel); add (resultLabel); setPreferredSize (new Dimension(300, 150)); } private class AddListener implements ActionListener{ public void actionPerformed (ActionEvent event){ int x, y, total; String text = input1.getText(); x = Integer.parseInt(text); text = input2.getText(); y = Integer.parseInt(text); total = x + y; resultLabel.setText (Integer.toString(total)); } } private class SubListener implements ActionListener{ public void actionPerformed (ActionEvent event){ int x, y, total; String text = input1.getText(); x = Integer.parseInt(text); text = input2.getText(); y = Integer.parseInt(text); total = x - y; resultLabel.setText (Integer.toString(total)); } } private class MultListener implements ActionListener{ public void actionPerformed (ActionEvent event){ int x, y, total; String text = input1.getText(); x = Integer.parseInt(text); text = input2.getText(); y = Integer.parseInt(text); total = x * y; resultLabel.setText (Integer.toString(total)); } } private class DivListener implements ActionListener{ public void actionPerformed (ActionEvent event){ int x, y, total; String text = input1.getText(); x = Integer.parseInt(text); text = input2.getText(); y = Integer.parseInt(text); total = x / y; resultLabel.setText (Integer.toString(total)); } } }
thanks for the help anyone and everyone

edit: for anyone who tries running the calculator: you have to type in numbers on both fields first, then you hit the button and it will calculate. You can't type one number, hit the button, then type another number. I'll change this soon, I just wanted to finish it first.