javacavaj
javacavaj

Reputation: 2971

Java - Layout Manager Selection

Is there a simply layout manager I can use in a JPanel to create something akin to a bar chart? FlowLayout almost meets this need. The added component orientation needs to be left to right (default for FlowLayout), but they need to "rest" on the bottom of the panel with excess space at the top (not available in FlowLayout). Also, the components will all the be the same height and width.

Thanks.

Upvotes: 1

Views: 610

Answers (5)

oxbow_lakes
oxbow_lakes

Reputation: 134270

You can do exactly what you want in GridBagLayout. Yes, I know everyone hates GBL; yes, I know I'll get down-voted. But it really is not difficult to understand and you can use it for almost any layout goal.

The trick to get a component to "stick" to the bottom is to use the anchor and fill properties of the GridBagConstraints object properly (i.e. SOUTH and NONE)

Upvotes: 1

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

If you are going to do something like a bar chart, you might want to consider not using Components at all. Just have a single JComponent that overrides (IIRC) paintComponent. It'll be easier to do the calculations in a manner appropriate to a bar chart rather than trying to use an inappropriate layout manager abstraction.

FWIW, I default to GridBagLayout, even if a simpler layout manager will do, on this basis that the code can be more consistent.

Upvotes: 1

lostiniceland
lostiniceland

Reputation: 3789

I actually prefer the FormLayout, since it is very flexible but you have to write a lot of code though. And in the beginning its a little bit confusing with its percentage and pixel parameters.

But you can for example tell a control that it is 5 pixels left of another control (thats the main part...it layouts controls in relation to neighbors), then it takes 100% of the lasting space availabel including a border space of 5 pixels (you need to use -5 then).

I think it looks somewhat similar to this

FormData data = new FormData();
data.left = new FormAttachement(neighborControl, 5);
data.right = new FormAttachement(100, -5);
...
button.setLayoutData(data);

This example is for JFace, but there are Swing implementations as well. I will look up my old code later this day to check if the code I wrote is right :)

Here´s a additional link

Upvotes: 0

Kevin Montrose
Kevin Montrose

Reputation: 22571

A BoxLayout might work for you. It lets you layout components left-to-right or top-to-bottom, with the tightly coupled Box class to force spacing constraints.

Upvotes: 0

camickr
camickr

Reputation: 324118

A BoxLayout will do the trick as demonstrated in this posting

Upvotes: 3

Related Questions