简体   繁体   中英

Simple Java Labels Event Driven Programming

for this i have all the code except for the last part (it may be a little un- organised but it works) The code just needs me to print the label of the button that has been clicked. (according to my professor the last part is the only thing that needs editing)

Here's the code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*; // added this import

public class lab6 extends JFrame{


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


        JButton b1 = new JButton ("Button 1");
        JButton b2 = new JButton ("Button 2");
        JButton b3 = new JButton ("Button 3");
        JButton b4 = new JButton ("Button 4");
        JButton b5 = new JButton ("Button 5");
        JButton b6 = new JButton ("Button 6");

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


        Buttonz bh = new Buttonz();


        // add buttons to panels
        panel1.add(b1);
        panel1.add(b2);
        panel1.add(b3);
        panel2.add(b4);
        panel2.add(b5);
        panel2.add(b6);


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

// registering button 1
        b1.addActionListener(bh);
        b2.addActionListener(bh);
        b3.addActionListener(bh);
        b4.addActionListener(bh);
        b5.addActionListener(bh);
        b6.addActionListener(bh);

    }

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


  class Buttonz implements ActionListener
  {
      @Override
      public void actionPerformed(ActionEvent e)
      {

        System.out.println(bh);
          // Use e.getActionCommand() to obtain the label of the button
          // Use System.out.println to display the label of the button

      }
  }
}

I will appreciate any help and assistance. Thank you! (:

Just change:

System.out.println(bh);

to

System.out.println(e.getActionCommand());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM