JPanel size by inner components - java

Is it possible to tell JPanel to set its size to fit all components that it contains? Something like pack() for JFrame.
edit: The trick with preferredSize didn't help. I've got JSplitPane, where in one part there is GridBagLayout with many labels (see screenshot) and labels overlap each other.
screenshot http://foto.darth.cz/pictures/screen.png

After looking at the source code for pack(), I came up with:
panel.setPreferredSize(panel.getPreferredSize());
This forces the panel to recalculate its preferred size based on the preferred sizes of its subcomponenents.
You may or may not have to call validate() afterward; in my tiny example, it seemed to make no difference, but the Javadoc says:
The validate method is used to cause a container to lay out its subcomponents again. It should be invoked when this container's subcomponents are modified (added to or removed from the container, or layout-related information changed) after the container has been displayed.
So I guess it depends on why you're having to repack your JPanel.

By default Containers have a preferred size that matches the preferred layout size given by the container. So literally all you have to do is:
panel.setSize(panel.getPreferredSize());
Presumably you are doing something odd with the parent to stop the parent's layout manager doing the equivalent of this.

maybe you can do something like that by removing from your panel
setResizable(false);

I would try:
panel.revalidate();
panel.repaint();
This will not necessarily set the panel to its preferred size, that is more dependent on what the layout manager decides to use.
This is useful in cases where you have added/removed components from a panel that is currently displayed and visible.
Update:
Based on your screenshot I can say the following:
1) Consider programatically changing the divider location.
2) Consider programatically resizing the window itself horizontally since it seems to be a little tight to show both sides of the split pane.
Or both.
You can set the divider location by doing
splitPane.setDividerLocation(newSize);
Keep in mind that there are two overloaded methods for this, one taking a float one taking an int. The float does a percentage of the size while the int is the size in pixels. The size is for the left hand panel (or top panel for that orientation).
I would consider possibly changing the divider location based on the preferred width of the panels.

The javax.swing mysteries reveal themselves only gradually, and only to those who are prepared to offer many libations (particularly torn out clumps of hair, hours burning the midnight oil, etc.) to the gods of Swing.
However, for this case in point I would suggest the following as a sort of Swiss army knife which usually does what you think the framework should do anyway:
myJPanel.getTopLevelAncestor().validate()
As the sacred text says, "Validates this container and all of its subcomponents." (Container.validate). NB getTopLevelAncestor() is a JComponent method.
Can't remember how JSplitPane fits into this: try it and you'll probably find that it validates both components (right and left, top and bottom), but I would be surprised if changing the divider doesn't do this for you anyway.

I had a similar issue using Netbeans GUI Builder. My inner panels were getting weird sizes; I was trying to adjust the minimum and preferred sizes manually, which was a frustrating exercise.
The problem was solved when I reset all the minimum and preferred sizes back to default (In Netbeans GUI Builder: right click JPanel component -> Properties -> preferredSize -> Reset to Default). When there is no imposed size, the jpanel takes the size of the inner component.
Note: GridBaLayout was used in my case

JSplitPanes are a bit fussy when it comes to its children's sizes, have a look at the Java tutorial. Are you using the GridBagLayout correctly? Looks like it's not setting the right JPanel's minimum size properly.

Here's an example of a panel which:
Resizes with it's parent.
Sets the width to the width of the parent.
Sets the height according to sum of the height of all of it's children.
JPanel panel = JPanel(new GridBagLayout())
panel.setMaximumSize(new Dimension(panel.getMaximumSize().width, panel.getPreferredSize().height))
panel.validate()
panel.repaint()

Related

How do I determine the minimum width of a JFrame to hide the horizontal scrollbar?

When I create a JFrame with child components, it opens to the smallest possible width a window can be, when I expected the width to be the minimum size to display the contents of the window without horizontal scroll bars.
How do I determine what that minimum size should be? Obviously something in the UI knows, because when made wide enough, the horizontal scroll bar disappears. This is the state I want the window when created. How do I fetch that number, which I suspect I would return as an override to getPreferredSize? As far as a preferred height, that's arbitrary.
As much as I know, when you use the pack() method, it automatically chooses the minimum size needed for all the components in-hand.
In another question, this subject is covered:
The pack method sizes the frame so that all its contents are at or
above their preferred sizes. An alternative to pack is to establish a
frame size explicitly by calling setSize or setBounds (which also sets
the frame location). In general, using pack is preferable to calling
setSize, since pack leaves the frame layout manager in charge of the
frame size, and layout managers are good at adjusting to platform
dependencies and other factors that affect component size.
From Java tutorial

Create a custom JComponent with fixed aspect ratio

As part of a project, I have a custom JComponent that implements a piece of a user interface. It's a rather strange control involving moving around a set of x-y points, but that shouldn't really matter, because that has been implemented and works properly.
This component has a usable area which is square -- any excess area is letterboxed away.
How can I tell a layout manager that I want this component to be square, of whatever size the layout manager decides is appropriate? It doesn't break functionality of extra area is allocated, but it does waste space that could better be used by other components.
You have only three knobs to tell the LayoutManager what your component wants:
getPreferredSize();
getMinimumSize();
getMaximumSize();
Note that not all LayoutManagers honor (especially the latter two) those hints. Apart from that the client using the component in a Layout has much more options with some LayoutManagers (e.g. GridBagLayout) to hint if and how the control is to be resized.
So in short, return a proper preferred size and leave the rest to the layout using the component.
This is a little crude but may be required. You can readjust the size according to what the user changed it to. For example, if the user adjusts the size to 500x600 set it to 500x500.

Java Swing - Dynamic List that Fills Available Space?

This doesn't seem like it should be very hard but I can't figure out how to do this:
I have a subclass of JPanel. It has a fixed height, but can be any width. The subclasses, on construction, set their preferred size using setPreferredSize(), which means I have to provide a width in addition to the height.
I would like to make a scrolling list of some number of my subclass, where the subclasses all fill the available horizontal space.
Right now I have a scroll view containing a JPanel containing my subclasses. The containing JPanel uses a BoxLayout with a vertical orientation.
Vertically, it looks great. Horizontally, my custom panels are just stuck at the preferred size. What would be the easiest way to make my panels fill the available horizontal space? I tried writing some layout listeners for them, but the performance was flakey (it seems that sometimes the event messages get dropped?) and the code looked hacky. Other views, such as the JList, JTree, and scroll views seem to resize automatically to fill the available space in a BoxLayout, so I feel like there must be something I can do in my JPanel subclass that I haven't thought of.
I'm open to using another Layout Manager if something else is better suited for this. I looked at GridBagLayout, but that seemed more geared towards static layouts where components aren't added and removed at runtime.
Edit: I found this on Oracle's Documentation for BoxLayout which has an example that looks exactly like what I want:
What if none of the components has a maximum width? In this case, if all the components have identical X alignment, then all components are made as wide as their container. If the X alignments are different, then any component with an X alignment of 0.0 (left) or 1.0 (right) will be smaller. All components with an intermediate X alignment (such as center) will be as wide as their container. Here are two examples:
Could someone show me the code that will produce the same results? The example code in the documentation doesn't look like it covers this particular picture.
When you put your component in a JScrollPane, your component may implement the Scrollable interface to adjust the scrollpane’s behaviour. By doing this you can implement the method getScrollableTracksViewportWidth() to return true so your component will always have the available width and be scrollable in vertical direction only.
This is how JList, JTable, JTree, and all the text components of Swing do it.
Alright - I found the problem. It appears that the default implementation of getMinimumSize() and getMaximumSize() will simply return the value of getPreferredSize() if it is set. So by setting a preferred size without a maximum size, my maximum size was the preferred size. By overriding getMaximumSize() to return (99999, preferredHeight), it now works exactly as I want.

Limiting a JScrollPane's scroll range

I have a JTextArea wrapped in a JScrollPane, which I use to log my application's output. I'm using the default, plain font with a size of 9 for the text area, and the scroll pane's height is 48 px. This results in an even distribution of lines in the scroll pane view, but there's a problem: if you scroll all the way up or all the way down, this happens:
As you can see, the top line got cut off, which is why I'm wondering if there's a way to limit the scroll pane's scroll range so it, for example, can't reach the top or bottom 6 pixels. Alternative solutions are also welcome.
You could change the margin (top/bottom) of your JTextArea by setting a custom Border using the method setBorder inherited from JComponent. The documentation for JComponent suggests the following:
Although technically you can set the border on any object that
inherits from JComponent, the look and feel implementation of many
standard Swing components doesn't work well with user-set borders. In
general, when you want to set a border on a standard Swing component
other than JPanel or JLabel, we recommend that you put the component
in a JPanel and set the border on the JPanel.
That would yield the same result as limiting the scroll range, while being more straight forward.
EDIT:
OP reported that the following solution worked for him:
textAreaLog.setBorder(BorderFactory.createEmptyBorder(0, 6, 0, 6));
Place the JTextArea in a JPanel with empty borders where top and bottom insets are 6 pixels?

Resizing a JPanel with resampling to preserve content

Give that I have written a JPanel with many different components on it, is there a way to apply an overall "dilate" ability on the panel so that everything in it stretches proportionally when I resize my window?
That is, if I manually resize my window to be 1/4 the size, everything in the panel should also shrink by 1/4 so the new panel is just a dilation of the first. Given that I have not designed the individual components inside to do this (there are many) is there any easy way to make the panel behave this way?
UPDATE: In order to be more clear on the solution I need, I will describe the panel contents:
The panel is a "game" of sorts, with a single null-layout and dozens of ImageIcons flying around the screen at any time. The ImageIcons are preloaded PNG files, which already have a permanent size. Of course, I could manually resize each ImageIcon and reposition them relative to window size, but that would involve recoding many components.
There are no buttons or text to worry about, so what I'm really looking for is some kind of "postprocessed" resize where the panel simply shrinks whatever's rendered by some porportion (think of resizing an image in Photoshop).
One option is of course to give up swing all together and use some 3rd party widget component library which draws itself using any Graphics. Then you can either draw the widgets on the image and resize the image, or, better yet, apply a transform to the graphics object you pass to the library.
If you do want to stick with swing there is the SwingUtilities.paintComponent method, which you could use to paint the Panel onto a BufferedImage which you could then resize. (I've used this myself to do some nice transitions between "views" in a game.)
The problem is of course that you somehow need to translate the user input accordingly. I have no solution for this right now, but the above perhaps helps you in some way.
You can try to override paintChildren() method of the panel and scale graphics to achieve desired visible size.
You could try J(X)Layer, see http://www.pbjar.org/blogs/jxlayer/jxlayer40/
Using layout managers instead of absolute positioning of the widgets will give you this behaviour. See the oracle tutorials: Using Layout Managers.
Do you really want fonts to resize on resize events? I don't know a layout manager which will do that for you.

Categories