gpt4 book ai didi

java - 创建动态 JLabel 和 JButton

转载 作者:行者123 更新时间:2023-11-29 07:12:41 25 4
gpt4 key购买 nike

我正在尝试根据属性文件中定义的 URL 数量创建动态 JButtonJLabel

到目前为止我尝试过的是:

AppResources.properties file

urls=http://google.com,http://stackoverflow.com,http://gmail.com
urlLabels=Internet Users,MPLS Users,Physical Access (Not Advised)

在我的 Java 程序中,我正在读取属性文件并根据 comma separator 拆分字符串,现在我需要相应地生成按钮和标签。像 first URL Label --> first URL as Button 等等。

到目前为止我这样做的方式是:

String url = properties.getProperty("urls");
String urlLabel = properties.getProperty("urlLabels");
String[] jButton = url.split(",");
String[] jLabel = urlLabel.split(",");


for (int i = 0; i < jLabel.length; i++) {
JLabel labels = new JLabel(jLabel[i]);
panel.add(labels);
for (int j = 0; j < jButton.length; j++) {
JButton button = new JButton(jButton[j]);
panel.add(button);
}
}

但是它为标签打印了三次按钮。如何解决这个问题?还有如何为这些按钮编写 Action 监听器?

最佳答案

如果您想为您的按钮实现 Action 监听器,您可以在创建按钮时简单地创建并添加一个新的 ActionListener。

示例:

for (int i = 0; i < jLabel.length; i++) {
final String str = jLabel[i];
JLabel labels = new JLabel(str);
panel.add(labels);
JButton button = new JButton(jButton[i]);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(panel, str);
}
});
panel.add(button);
}

关于java - 创建动态 JLabel 和 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12367074/

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