I’m new in Java and I’m finding it hard to implement a GUI here unlike in Visual Basic.
import javax.swing.*;
import java.awt.*;
public class CalculatorGui extends JFrame{
private static final int WIDTH = 250;
private static final int HEIGHT = 250;
private JTextField enterTextField;
private JButton sevenB, eightB, nineB, divideB, fourB, fiveB, sixB, multiplyB, oneB, twoB, threeB, subtractB, zeroB, dotB, equalsB, addB;
public CalculatorGui() {
setTitle("Calculator");
setSize(WIDTH, HEIGHT);
setLayout(new GridLayout(4, 4));
enterTextField = new JTextField(30);
sevenB = new JButton("7");
eightB = new JButton("8");
nineB = new JButton("9");
divideB = new JButton("/");
fourB = new JButton("4");
fiveB = new JButton("5");
sixB = new JButton("6");
multiplyB = new JButton("*");
oneB = new JButton("1");
twoB = new JButton("2");
threeB = new JButton("3");
subtractB = new JButton("-");
zeroB = new JButton("0");
dotB = new JButton(".");
equalsB = new JButton("=");
addB = new JButton("+");
/*JPanel dataPanel = new JPanel();
JPanel buttonPanel = new JPanel();
FlowLayout flowCenter = new FlowLayout(FlowLayout.RIGHT);
GridLayout aGrid = new GridLayout(4, 4);
buttonPanel.setLayout(flowCenter);
dataPanel.setLayout(aGrid);
dataPanel.add(enterTextField);
buttonPanel.add(sevenB);
buttonPanel.add(eightB);
buttonPanel.add(nineB);
buttonPanel.add(divideB);
buttonPanel.add(fourB);
buttonPanel.add(fiveB);
buttonPanel.add(sixB);
buttonPanel.add(multiplyB);
buttonPanel.add(oneB);
buttonPanel.add(twoB);
buttonPanel.add(threeB);
buttonPanel.add(subtractB);
buttonPanel.add(zeroB);
buttonPanel.add(dotB);
buttonPanel.add(equalsB);
buttonPanel.add(addB);
add(dataPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);*/
//add(enterTextField);
add(sevenB);
add(eightB);
add(nineB);
add(divideB);
add(fourB);
add(fiveB);
add(sixB);
add(multiplyB);
add(oneB);
add(twoB);
add(threeB);
add(subtractB);
add(zeroB);
add(dotB);
add(equalsB);
add(addB);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
CalculatorGui calcu = new CalculatorGui();
}
}
It runs but I need to put a text field right before those buttons (numbers). The text field should flow and will not be enlarged when the window is maximized (unlike the 4×4 buttons). I’ve tried JPanel (see comments) but it outputs a horrible design. P
Here you go, with some rules to follow while building GUI (rules):
Do not subclass AWT/Swing/X Components for application needs
I would suggest you to use WindowsBuilder Pro after a good manual practice with some
layoutsandcomponents