为此我拥有除最后一部分之外的所有代码(它可能有点没有组织但是它有效)代码只需要我打印已点击的按钮的标签。 (据我的教授说,最后一部分是唯一需要编辑的东西)
以下是代码:
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
}
}
}
我将不胜感激任何帮助和帮助。谢谢! (:
答案 0 :(得分:0)
只需改变:
System.out.println(bh);
到
System.out.println(e.getActionCommand());