我想将 JButton、JTextField、JTextArea 等组件存储在同一个 ArrayList 中,然后循环遍历它并将每个组件添加到 JFrame 中。我尝试将它们存储在 ArrayList 中,但是当我循环遍历它并将其包含的每个组件添加到我的框架中时,框架中没有显示任何内容。有谁知道如何做到这一点?提前致谢。
最佳答案
继续这个:
public class Example {
public static void main(String[] args) {
JFrame frame = new JFrame();
List<Component> components = new ArrayList<Component>();
components.add(new JButton("test1"));
components.add(new JButton("test3"));
components.add(new JButton("test3"));
frame.setLayout(new FlowLayout());
for(Component component: components)
frame.getContentPane().add(component);
frame.pack();
frame.setVisible(true);
}
}
- 向框架添加布局管理器
- 调用
pack()
根据您的组件调整框架大小 - 将框架设置为可见
关于java - 将组件存储在 ArrayList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10389470/