GridBagLayout display problem
I am working on a GUI for a calculator. Since the GUI elements are of different sizes (e.g. I want the screen to extends all the way across the top of the GUI, while the buttons should be in a 4x4 grid below it), I have decided to use GridBagLayout. However, when I display the GUI, the screen and buttons are all in one row.
Here is a fragment of the code containing the screen and the first row of buttons:
Code Java:
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.lang.*;
public class CalculatorGUI extends JFrame
{
JButton button;
JButton plus;
JTextField screen = new JTextField("0", 15);
//ActionListener al = new ArithmeticListener(this);
CalculatorGUI()
{
setSize(350, 350);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 4;
add(screen);
gbc.gridwidth = 1;
button = new JButton("7");
gbc.gridx = 0;
gbc.gridy = 1;
//button.addActionListener(al);
add(button);
button = new JButton("8");
gbc.gridx = 1;
gbc.gridy = 1;
//button.addActionListener(al);
add(button);
button = new JButton("9");
gbc.gridx = 2;
gbc.gridy = 1;
//button.addActionListener(al);
add(button);
button = new JButton("+");
gbc.gridx = 3;
gbc.gridy = 1;
//button.addActionListener(al);
add(button);
}
}
I've also tried declaring and initializing the buttons and separate variables, but, when I do, the JVM throws a NullPointerException, (I assume) because it somehow reads the variable as uninitailized. I am still unsure if I am using GridBagLayout correctly and I often get confused as to how to correctly specify the location of a component in the layout, so any help would be greatly appreciated.