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.
panel1.add(new JButton(...))
, JButton myButton = new JButton(...)
; and then panel1.add(myButton);
addActioListener(...)
method, and have the ActionListener print the ActionEvent's getActionCommand() String. The ActionEvent is the parameter passed into the actionPerformed(ActionEvent e)
method.