为此,我有所有的代码,除了最后一部分(它可能有点杂乱无章,但它可以工作),代码只需要我打印标签的按钮已被点击。(根据我的教授的说法,最后一部分是唯一需要编辑的部分)
代码如下:
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
}
}
}我将感谢任何人的帮助和帮助。谢谢!(:
发布于 2014-05-01 07:25:55
只需更改:
System.out.println(bh);至
System.out.println(e.getActionCommand());https://stackoverflow.com/questions/23399720
复制相似问题