我使用 DesignGridLayout java 库(这里)创建网格布局。如果创建 3 列布局,则在示例中。
使用此代码:
layout.row().add(new JButton("Button 1")).add(new JButton("Button 2")).add(new JButton("Button 3"));
或使用返回对象的方法:
layout.row().add(button()).add(button()).add(button());
...
...
public JButton button() {
return new JButton("Button");
}
问题是,如何动态创建 JButton 值?可能是名称、图标或任何东西?
我已经尝试过我自己的代码:
for (int i=0; i<4; i++) {
JButton button = new JButton();
layout.row().add(button).add(button).add(button);
}
它返回: 线程“AWT-EventQueue-0”中的异常 java.lang.IllegalArgumentException:不要两次添加相同的组件
我在面板中添加的每个组件中使用不同值的目的是,我想创建填充不同图像的画廊,并使用循环加载这些图像,如下所示:
for(int i=0; i<files.length; i++) {
...
ImageIcon imgSource = new ImageIcon(new File(myPath));
JLabel labelGallery = new JLabel(imgSource);
...
}
有什么解决办法吗?谢谢之前:)