I may just be totally misusing GridBagLayout, but, given the tutorials I have read, I don't understand how I might be.
The code is:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonsGUI extends JFrame { JButton button; JLabel label = new JLabel("No buttons clicked"); Flash flash; ActionListener bl; ButtonsGUI() { setSize(275, 275); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); setLayout(new GridBagLayout()); GridBagConstraints con = new GridBagConstraints(); bl = new ButtonsListener(this); //flash = new Flash(label); con.gridx = 0; con.gridy = 0; con.gridwidth = 2; add(label); button = new JButton("Left"); con.gridx = 0; con.gridy = 1; con.gridwidth = 1; button.addActionListener(bl); add(button); button = new JButton("Right"); con.gridx = 1; con.gridy = 1; con.gridwidth = 1; button.addActionListener(bl); add(button); } } class ButtonsListener implements ActionListener { String butStr; String labStr; String newStr; JLabel lab; ButtonsListener(ButtonsGUI bg) { lab = bg.label; } public void actionPerformed(ActionEvent ae) { butStr = ae.getActionCommand(); labStr = lab.getText(); if (labStr.equals("No buttons clicked")) { newStr = labStr.substring(2, 9) + labStr.substring(10, 18); if (butStr.equals("Left")) { lab.setText(butStr + newStr); } else if (butStr.equals("Right")) { lab.setText(butStr + newStr); } } else if (labStr.equals("Left button clicked")) { newStr = labStr.substring(4, 19); if (butStr.equals("Right")) { lab.setText(butStr + newStr); } } if (labStr.equals("Right button clicked")) { newStr = labStr.substring(5, 20); if (butStr.equals("Left")) { lab.setText(butStr + newStr); } } } } class Buttons { public static void main(String args[]) { new ButtonsGUI(); } }
Currently, all the elements are displaying in the same row. I thought that I had correctly used the constraints to specify column and row, but, apparently, I don't know how to specify constraints.