I am trying to practice my OOP skills along with Java Swing but I am currently stuck. I am trying to make a calculator gui kind of like the one you'd see on a phone. I don't know how I should be implementing the functions of each button press. For now I am just trying to display the number on the screen (JLabel object) when I press a button. I have also attached a picture of the GUI that I have so far.
Should I be implementing the functions in a separate .java file? Or should they be implemented in the Calculator.java or Keyboard.java file?
Also how are they implemented because I don't know how to display on the JLabel object in the Calculator.java file if my button objects are in the Keyboard.java file.
Calculator.java
package calculator;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculator extends JFrame
{
public static void main(String[] args)
{
new Calculator();
}
public Calculator() //Calculator constructor??
{
setLayout(new GridLayout(2,1));
this.setSize(400,600);
this.setLocationRelativeTo(null); //center the window
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel display = new JLabel();
this.add(display);
Keyboard kb = new Keyboard();
this.add(kb);
this.setVisible(true);
}
}
Keyboard.java
package calculator;
import javax.swing.JPanel;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Keyboard extends JPanel implements ActionListener
{
public Keyboard()
{
setLayout(new GridLayout(4,4));
JButton one = new JButton("1");
this.add(one);
JButton two = new JButton("2");
this.add(two);
JButton three = new JButton("3");
this.add(three);
JButton plus = new JButton("+");
this.add(plus);
JButton four = new JButton("4");
this.add(four);
JButton five = new JButton("5");
this.add(five);
JButton six = new JButton("6");
this.add(six);
JButton minus = new JButton("-");
this.add(minus);
JButton seven = new JButton("7");
this.add(seven);
JButton eight = new JButton("8");
this.add(eight);
JButton nine = new JButton("9");
this.add(nine);
JButton times = new JButton("x");
this.add(times);
JButton zero = new JButton("0");
this.add(zero);
JButton clear = new JButton("clear");
this.add(clear);
JButton equals = new JButton("=");
this.add(equals);
JButton divide = new JButton("/");
this.add(divide);
}
public void actionPerformed(ActionEvent e) {
}
}