Search code examples
javaswingjpaneljbuttonactionlistener

Java Button Layouts and Displays


My objective here is to display a message to the console, showing which button I have pressed (the buttons go from 1-6). This is the furthest I have gotten.

CODE:

public class excercise5_1 extends JFrame {


    public excercise5_1() {
        setLayout(new FlowLayout());

        // Create two panels
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();


        // Add three buttons to each panel
        panel1.add(new JButton(" Button 1 "));
        panel1.add(new JButton(" Button 2 "));
        panel1.add(new JButton(" Button 3 "));
        panel2.add(new JButton(" Button 4 "));
        panel2.add(new JButton(" Button 5 "));
        panel2.add(new JButton(" Button 6 "));


        // Add panels to frame
        add(panel1);
        add(panel2);

    }

    public static void main(String[] args) {
        excercise5_1 frame = new excercise5_1();
        frame.setTitle(" Exercise 12_1 ");
        frame.setSize(600,75);
        frame.setLocationRelativeTo(null); // center frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

I just don't know what to do to make it display "Button 2" if I press it.


Solution

    1. Don't create your JButton's inline -- in the add method parameter. So not panel1.add(new JButton(...)),
    2. Instead create your JButton on its own line: but rather JButton myButton = new JButton(...); and then panel1.add(myButton);
    3. Use a for loop to simplify things.
    4. Add an ActionListener to your button via its addActioListener(...) method, and have the ActionListener print the ActionEvent's getActionCommand() String. The ActionEvent is the parameter passed into the actionPerformed(ActionEvent e) method.
    5. Read the JButton tutorials as it's all spelled out for you there. It appears as if you've read nothing about JButtons yet.