Rohit Malish
Rohit Malish

Reputation: 3229

Store components in ArrayList

I want to store components like JButton, JTextField, JTextArea etc. all in same ArrayList and later loop through it and add every component to JFrame. I tried storing them in ArrayList but when I looped through it and added every component it included to my frame, nothing showed up in frame. Does anyone know how this can be done? Thanks in advance.

Upvotes: 0

Views: 3663

Answers (3)

ceklock
ceklock

Reputation: 6372

Do you know how to use Layout Managers?

A layout manager is an object that implements the LayoutManager interface* and determines the size and position of the components within a container. Although components can provide size and alignment hints, a container's layout manager has the final say on the size and position of the components within the container.

Using Layout Managers

Upvotes: 1

Óscar López
Óscar López

Reputation: 236112

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.

Upvotes: 1

Thomas Uhrig
Thomas Uhrig

Reputation: 31613

go ahead with this:

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);
}
}
  • add a layout manager to your frame
  • call pack() to resize the frame according to your components
  • set the frame visible

Upvotes: 1

Related Questions