gpt4 book ai didi

Java 按钮布局和显示

转载 作者:行者123 更新时间:2023-11-29 05:25:09 27 4
gpt4 key购买 nike

我的目标是向控制台显示一条消息,显示我按下了哪个按钮(按钮从 1 到 6)。这是我得到的最远的。

代码:

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);
}
}

我只是不知道该怎么做才能让它在我按下时显示“按钮 2”。

最佳答案

  1. 不要在 add 方法参数中创建 JButton 的内联。所以不是 panel1.add(new JButton(...)),
  2. 而是在自己的行上创建 JButton:而是 JButton myButton = new JButton(...);然后是 panel1.add(myButton);
  3. 使用 for 循环来简化事情。
  4. 通过 addActioListener(...) 方法将 ActionListener 添加到您的按钮,并让 ActionListener 打印 ActionEvent 的 getActionCommand() 字符串。 ActionEvent 是传递给 actionPerformed(ActionEvent e) 方法的参数。
  5. 阅读JButton tutorials因为这一切都在那里为你拼写出来。看起来好像您还没有读过有关 JButton 的任何内容。

关于Java 按钮布局和显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22975993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com