I want all of my buttons to be the same size. The one with text "Open Save" is the widest, so I want to use that one as the metric for resizing the other buttons. However, when I have this line of code in the program, the button won't display: newButton.setPreferredSize (openSaveButton.getSize ());
Here's the full program so far:
public class Project1 implements ActionListener {
// The frames
private JFrame mainMenu = new JFrame("Main Menu");
private JPanel mainPanel = new JPanel();
private JFrame game = new JFrame("Game");
private JPanel gamePanel = new JPanel();
// Controls
private JButton newButton = new JButton("New");
private JButton openSaveButton = new JButton("Open Save");
private JButton exitButton = new JButton("Exit");
private JTextArea textArea = new JTextArea();
public static void main(String[] args) {
new Project1();
}
// Constructors
public Project1() {
mainPanel.setLayout(new GridBagLayout());
addItem(mainPanel, newButton, 0, 0, 1, 1, GridBagConstraints.CENTER);
newButton.addActionListener(this);
newButton.setPreferredSize(openSaveButton.getSize());
addItem(mainPanel, openSaveButton, 0, 1, 1, 1, GridBagConstraints.CENTER);
openSaveButton.addActionListener(this);
addItem(mainPanel, exitButton, 0, 2, 1, 1, GridBagConstraints.CENTER);
exitButton.addActionListener(this);
mainMenu.add(mainPanel, BorderLayout.NORTH);
openFrame(mainMenu, 10, 10, JFrame.EXIT_ON_CLOSE);
gamePanel.setLayout(new GridBagLayout());
addItem(gamePanel, textArea, 0, 0, 1, 1, GridBagConstraints.CENTER);
openFrame(game, 200, 10, JFrame.DO_NOTHING_ON_CLOSE);
}
// Setters
// Getters
// ActionListener override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newButton) {
newGame();
} else if (e.getSource() == openSaveButton) {
openFile();
} else if (e.getSource() == exitButton) {
System.exit(0);
}
}
// Other functions and procedures
private void openFrame(JFrame what, int x, int y, int operation) {
what.pack();
what.setLocation(x, y);
what.setVisible(true);
what.setResizable(false);
what.setDefaultCloseOperation(operation);
}
private void addItem(JPanel p, JComponent c, int x, int y, int width, int height,
int align) {
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(5, 5, 5, 5);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
private void newGame() {
}
private void openFile() {
}
}
Here are two screen shots of what happens, without the line and with: