gpt4 book ai didi

java - 使用正确的 if 子句向我的 JButton 添加操作

转载 作者:行者123 更新时间:2023-12-01 18:11:20 25 4
gpt4 key购买 nike

try {
for (int i = 0; i < 148; i++) {
zx = zx+1;
if (zx==15) {
zx = 0;
zy = zy+1;
gbc.gridheight = zy;
} // end of if
gbc.gridwidth = zx;
JButton b = new JButton(champs[i]);
cp.add(b, gbc);
b.setName(champs[i]);
if (b.getModel().isPressed()) {
System.out.println(b);
} // end of if
}
} catch(Exception e) {
System.out.println(e);
}

我正在尝试向我的 148 个 JButton 添加操作/响应(如果它们被按下),但似乎我使用了错误的 if 子句。布局工作完全正常,所有按钮都以正确的名称显示在正确的位置,但我无法向它们添加操作。我仍然是一个java初学者,所以请记住这一点。任何帮助表示赞赏。提前致谢。

最佳答案

您需要 Action 监听器。

创建并初始化 JButton 后,您需要向其添加事件监听器。如果您使用的是 GUI 构建器,您可以进入设计模式并右键单击按钮,然后转到“操作/执行操作”,它将为您创建方法,您可以在其中输入代码。

如果您正在编写 swing 应用程序,则可以初始化按钮,然后手动向其添加事件监听器。例如:

    private JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//insert code here
}
});

关于java - 使用正确的 if 子句向我的 JButton 添加操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60464600/

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