0

我想将 JButton、JTextField、JTextArea 等组件存储在同一个 ArrayList 中,然后循环遍历它并将每个组件添加到 JFrame。我尝试将它们存储在 ArrayList 中,但是当我遍历它并将它包含的每个组件添加到我的框架中时,框架中什么都没有显示。有谁知道如何做到这一点?提前致谢。

4

3 回答 3

1

Try declaring the ArrayList like this:

List<JComponent> = new ArrayList<JComponent>();

The above works because JComponent is a common ancestor for JButton, JTextField, JTextArea - that is, it's a super class common to all JComponents.

It's not clear to me: why do you want to add the components first to an ArrayList? add them directly to the JFrame.

于 2012-04-30T19:40:56.377 回答
1

继续这个:

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()以根据您的组件调整框架的大小
  • 设置框架可见
于 2012-04-30T19:43:05.440 回答
1

你知道如何使用布局管理器吗?

布局管理器是实现 LayoutManager 接口*并确定容器内组件的大小和位置的对象。尽管组件可以提供大小和对齐提示,但容器的布局管理器对容器内组件的大小和位置拥有最终决定权。

使用布局管理器

于 2012-04-30T19:50:21.020 回答