llm
llm

Reputation: 5669

Java Container constraints question

I am using the following:

java.awt.Container.add(Component comp, Object constraints)

How do I specificy the constraints object? I need to be able to place a component within the container.

Oh and my class extends JInternalFrame if this helps...

I need to specify coordinates to place the component within the container

Upvotes: 6

Views: 12202

Answers (5)

Jack
Jack

Reputation: 133587

The constraints objects depends on which layout manager you are using.

For example, with a BorderLayout you will have just some constants: container.add(element, BorderLayout.CENTER)

While if the layout manager of the container is a GridBagLayout you will have a GridBagConstraints object with the specified parameters.

Some layout managers (like FlowLayout or GridLayout) don't need any kind of constraint since they actually decide how to place things by themselves.

As a side note, if you need absolute positioning you will not have any layout manager:

container.setLayout(null);
container.add(element1);

Insets insets = pane.getInsets();
element1.setBounds(..); //here you set absolute position

Upvotes: 3

Andreas Dolk
Andreas Dolk

Reputation: 114787

From java.awt.Container class'es javadoc:

The constraints are defined by the particular layout manager being used. For example, the BorderLayout class defines five constraints: BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.EAST, BorderLayout.WEST, and BorderLayout.CENTER.

The GridBagLayout class requires a GridBagConstraints object. Failure to pass the correct type of constraints object results in an IllegalArgumentException.

This comment can be found at the protected addImpl method.

Upvotes: 1

Carl Smotricz
Carl Smotricz

Reputation: 67760

Look at the tutorials for LayoutManagers! The examples will show you which constraints are used with which layouts, and how.

Upvotes: 5

aioobe
aioobe

Reputation: 421030

The proper constraints object depends on the current LayoutManager.

If you're using BorderLayout for instance, the constraints object could for instance be BorderLayout.SOUTH.

Upvotes: 0

Jeff Storey
Jeff Storey

Reputation: 57192

It depends on the layout manager you are using. For example, if you are using a BorderLayout, then you could use values like BorderLayout.CENTER and BorderLayout.NORTH. If you are not using a layout manager, then you need to set the position of the components manually.

Upvotes: 0

Related Questions