我有 12 个按钮,每个按钮上都有我家人的名字。我想让按钮起作用。当用户点击他们的名字时,我希望弹出一条消息并说“你好(无论名字)!” 我的代码如下。你能告诉我如何让这些按钮按我想要的方式工作吗?提前致谢。
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.GridLayout;
public class NameButtons{
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Pick A Name");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonPanel = new JPanel();
JPanel containerPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4,6));
buttonPanel.add(new JButton("Stephanie"));
buttonPanel.add(new JButton("Dwayne"));
buttonPanel.add(new JButton("Jennifer"));
buttonPanel.add(new JButton("Brian"));
buttonPanel.add(new JButton("Joseph"));
buttonPanel.add(new JButton("Justin"));
buttonPanel.add(new JButton("Raine"));
buttonPanel.add(new JButton("Hunter"));
buttonPanel.add(new JButton("Grayson"));
buttonPanel.add(new JButton("Abel"));
buttonPanel.add(new JButton("Janice"));
buttonPanel.add(new JButton("Bob"));
buttonPanel.setPreferredSize(new Dimension(300, 400));
containerPanel.add(buttonPanel);
frame.getContentPane().add(containerPanel);
frame.pack();
frame.setVisible(true);
}
}