How to set only the preferred width of Panel with flow layout? - java

I have a panel with flow layout, and it can contain a variable number of items - from 1 to 2000. I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width. The problem is, when I set preferred size of panel to something like (800,600), some items are missing, and there is no scroll. If I set up preferred size of scroll pane, then all elements in flow pane are put on one very long line.
Setting maximum size on any element seems to do nothing at all - layout managers ignore it.
How can I fix this?

I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width
You can use the Wrap Layout for this.
Don't set the preferred size of the panel. But you can set the preferred size of the scroll pane so the frame.pack() method will work.

You could use BoxLayout to do this:
JPanel verticalPane = new JPanel();
verticalPane.setLayout(new BoxLayout(verticalPane, BoxLayout.Y_AXIS));
JScrollPane pane = new JScrollPane(verticalPane);
//add what you want to verticalPane
verticalPane.add(new JButton("foo"));
verticalPane.add(new JButton("bar"));
This of course will use the preferred size of each component added. If you want to modify the preferred size for example of a JPanel, extend it and override getPreferredSize:
class MyPanel extends JPanel(){
public Dimension getPreferredSize(){
return new Dimension(100,100);
}
}
A note: BoxLayout will take in consideration getPreferredSize, other LayoutManager may not.
Please criticize my answer, I'm not sure it's completely correct and I'm curious to hear objections in order to know if I understood the problem.

Related

Make a panel resize dynamically in Swing

I'm creating an interface composed out of a box layout which contains panels inside every space.
In this specific case I've got a "cascade" of panels, the first is supposed to be a panel with a FlowLayout as layout manager, underneath it there's a GridLayout and under it there's supposed to be another label.
The thing is that I'd need the first panel to dynamically resize as the window get resized itself.
Here's the problem: I need the first panel to have a specific size in relation to the absolute size.. the thing is that I can't set my preferred size.. in the class I do the following but the panel stays the exact same size as before..
this.setPreferredSize(new Dimension(windowWidth, 50))
I'll send the code as soon as I get home, for now the situation is the one written above.
I need the first panel to have a specific size in relation to the absolute size
Your main panel should be a BorderLayout (which is the default layout of a JFrame), not a BoxLayout.
Then you add the panel that needs to be a specific size to the BorderLayout.NORTH of the frame.
Then your second panel can use a BoxLayout and add this panel to BorderLayout.CENTER of the frame. Now this panel will get all the extra space as the frame is resize.

Change the height of a panel at runtime

How to change the height of panel at runtime?
I have some panels inside a JFrame, I tried on one of them:
int w = panel.getWidth();
panel.setSize(w, 1000);
But there's no effect. What's wrong?
You may have to validate and repaint your panel. Try following:
int x=panel.getWidth();
panel.setSize(x,1000);
panel.validate();
panel.repaint();
Check out this answer:
set size wont work in java
"In Swing, you have two options for layout: do everything manually or let a LayoutManager handle it for you."
and
"Try calling setPreferredSize() and setMinimumSize()."
If you are using a layout manager (you probably are), the layout decides what to do with the
contained components. setPreferredSize() usually works because the layout usually asks the
contained components what their preferred sizes are, and then arranges the components
based on (among others) that information.
If you put the panel in a LayoutManager (i.e. the parent has a LayoutManager which is BorderLayout by default) that LayoutManager would override the size and thus your call would have no effect.
Try to call setLayoutManager(null) on the parent although I'd recommend using a LayoutManager and use setPreferredSize(), setMinimumSize() and setMaximumSize().
For changing width and height of JPanel use setPreferredSize method.
JPanel folderPanel = new JPanel();
folderPanel.setPreferredSize(new Dimension(245, 450));// width, height
You just set the visibility of this component (JPanel) as follow:
JPanel panel = new JPanel();
//set your custom size in this with=120; height=570;
panel.setSize(120,570);
panel.setVisible(false);
panel.setVisible(true);
//hope this help! :)

add a scrollable jpanel to a gridlayout

I'm building a grid filled with labels. One of them contains html-text and should resize to maximum format and be scrollable. I found how to add a JScrollPane but it stays one line height, I just can't find how to resize it even when I give it a size of 400x400 ...
Removing getViewport() gives the same result.
JPanel grid = new JPanel(new GridLayout(1,2));
// first cell of the grid
grid.add(new JLabel("title"));
// second cell of the grid, this should be the scrollable one
JScrollPane scroll = new JScrollPane();
scroll.getViewport().setSize(400, 400);
scroll.getViewport().add(new JLabel("<html>long<br>html<br>text</html>"));
grid.add(scrollVersion, BorderLayout.CENTER);
Any ideas ?
Thanks a lot ...
GridLayout does not respect preferred size of the components which it lays out. It aims to make all grid cells the same size. An alternative is to use GridBagLayout, however I personally would recommend ZoneLayout which (in my opinion) is simpler, just as powerful, and much more intuitive. With the cheatsheet you can't go wrong.
As a side note, BorderLayout.CENTER is a constraint used for BorderLayout and is not compatible with GridLayout. When components are added to the owner of a GridLayout, you need not provide constraints. Components are added left to right starting at the top left corner cell using GridLayout.
Replace your GridLayout with a GridBagLayout. With the correct set of constraints, it should work like a charm. And obviously, take a look at some examples, as GridBagLayout seems quite complex, but is rather simple with some examples.
All cells of the GridLayout are designed to have the same size, so if you want one to be bigger than teh othes you must use another LayoutManager, like the GridBagLayout that Riduel suggest.
Also if your JLabel is going to have more than one line i suggest you to replace it by an uneditable JTextPane o JTextArea

Problem with FlowLayout

public class MyFrame extends JFrame
{
public MyFrame(String title)
{
setSize(200, 200);
setTitle(Integer.toString(super.getSize().width));
setLayout(new FlowLayout());
for (int i = 0; i < 5; ++i)
{
JButton b = new JButton();
b.setSize(90,50);
b.setText(Integer.toString(b.getSize().width));
this.add(b);![alt text][1]
}
this.setVisible(true);
}
}
why if having button widht 90 I'm getting window where three buttons are in one row instead of two?
FlowLayout will lay out Components left-to-right (or right-to-left) wrapping them if required. If you wish to explicitly set the size of each JButton you should use setPreferredSize rather than setSize as layout managers typically make use of the minimum, preferred and maximum sizes when performing a layout.
Size properties are quite confusing - There is an interesting article here. In particular, note:
Are the size properties always
honored?
Some layout managers, such as
GridLayout, completely ignore the size
properties.
FlowLayout, attempts to honor both
dimensions of preferredSize, and
possibly has no need to honor either
minimumSize or maximumSize.
The FlowLayout just places component one beside the other in a left-to-right order. When the width reaches the one of the container that has that layout it simply wraps on the other line.
If you want to arrange them in a grid-style layout (like it seems you want) you can use the GridLayout that allows you to specify the number of columns and rows:
component.setLayout(new GridLayout(2,2))
The only downside of GridLayout is that every cell of the grid will be of the same size (which is usually good if you just have JButtons or JLabels but when you mix things it will be visually bad).
If you really need more power go with the GridBagLayout, very customizable but with a steeper learning curve at the beginning.
Probably your size problem is related to the fact that you are using setSize but in Swing these things have strange behaviours, you should try by setting setPreferredSize(200,200) instead of setSize. But don't ask me why!
NOTE: you should ALWAYS refer to the frame's content pane and not to the frame it self. When you set layout you should do getContentPane().setLayout(..), when you add items you should do getContentPane().add(..) and so on.
Errata: now every JFrame add, remove, setLayout automatically forward to the content pane.
For one thing, you're not using JFrame correctly: you don't add components directly to the frame, you add them to a JPanel that you then pass to the frame with setContentPane().
Also: it's not very elegant to directly subclass JFrame just to add components. Instead, create your frame as a separate object.

Scrollable flow panel

I need to create a panel where I can put some rectangles and it automatically reorder just inserting a scrollbar and growing up vertically. Also this panel can be resizable and again the rectangles must to be reordered to correctly be displayed inside the panel.
If I understand the question you want components to wrap to the next line so that the panel grows vertically while the width remains fixed.
If so then check out the WrapLayout
Note: the FlowLayout already supports the wrapping of components to a new row on the panel. This issue is that the preferred size calculation assumes all components are placed on a single row. The WrapLayout overrides the preferred size calculation to support the wrapping of components on a new row.
Use a JScrollPane. If you never want a horizontal scroll bar you can add the following:
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
(By default the scroll pane will add horizontal and vertical scroll bars when required.)
The scroll pane itself will only be resizeable if you add it to a Container with the appropriate layout manager; e.g.
JFrame frm = new JFrame();
frm.setLayout(new BorderLayout());
JScrollPane sp = new JScrollPane();
frm.add(sp, BorderLayout.CENTER); // Adding a component to the CENTER will cause the component to grow as the frame is resized.

Categories