Swing custon JComponent size - java

I want to create a custom JComponent (specifically a custom JToggleButton) that has a custom appearance. What i want to do is simply override the default painting of the component and draw something of my own (an image for instance)
This is NOT a question on how to do that (I am fairly proficient with Java2D). What i want to ask is what steps must i take to ensure that my component has the size i desire it to have?
The tests i have done so far have been problematic. I draw an image of lets say 200*100 pixels and the layout managers display only a part of my component. I tried setSize, setPrefferedSize, setMinimumSize and none of them worked.

There is no way in the Swing model to outright guarantee that you will be given a set amount of space - layout managers can and do ignore minimum and maximum sizes, though normally they only ignore one or the other.
If you have a fixed size component, you should override getMinimumSize, getPreferredSize and getMaximumSize to all return a dimension of that fixed size that you need. If you can scale to some extent adjust the minimum and maximum as required. Overriding the methods avoids some third party code calling the set*Size methods and overwriting your choices (layout managers will still call setSize to tell the component what size it was actually allocated which is normal). It also makes sure the sizes are set before the layout manager starts laying out the component.
If the size of your component can change after layout has occurred, you need to make sure you invalidate the component layout properly but avoid doing this if you can.

the size is determined by the LayoutManager. if you will use a null LayoutManager you will be able to force a specific size (and location). otherwise you can override getPreferedSize() which will be respected by some layout managers.

Related

Method called when layouting is done?

I'm looking for a method that I could override or some listener that is fired when a JPanel is being layouted. Checked the javadoc but couldn't find one. The situation is this:
I have a component that takes care about its contents via a Null-Layout.
The component itself is however layouted inside another JPanel (with a layout manager) and receives a certain size when layouting is done.
Now I want to use this size to calculate widths and heights of the contents of that Null-Layout JPanel.
But of course I need to know when I have to recalculate sizes. Any ideas or a good alternative approach? The required calculating in the Null-Layout is actually very simple and using a layout manager would probably require more work than the current solution - I just need to find that method or listener.
Answering myself so this can be closed.
doLayout will be called when layouting is needed, so that's the method one can override when doing layouts without a layout manager.

Auto resize swing elements to fit to the container's size

Not sure if what I need is possible.
I have a container (JPanel) that contains some internal elements.
I was wondering if it is possible to force internal elements to fit into the container's size.
I need them to be fully visible i.e., resize to fit inside the Panel's size and not cut some parts of the internal elements.
Scrolling is not an option.
Is this possible by using a Layout or something?
EDIT: Important clarification:
The thing is that I do not have access to the internal elements neither to their properties so I would say that a Layoutmanager capable of resizing child elements to fit to its size is needed. I tested BorderLayout and GridBagLayout but the result is always the same, the internal elements are cut out.
It's for exactly that reason that LayoutManagers exist. All the LayoutManagers work for simple containers directly, excluding GridBagLayout which is to able to handle most complete GUIs directly.
For most complete GUI's you have some choices as follows:
Look for a 3rd party layout such as MigLayout or here
Use GridBagLayout
Very easy way is use nested layout, where there is more than one JPanel and each has child JPanels with the same or different LayoutManager
Or custom layout, should be hard..., but same as using GridBagLayout
You could set the JPanel layout to border layout, then add the single child to the center. If there are multiple children, this approach becomes less useful since components added to the the NORTH, SOUTH, EAST, and WEST will remain statically sized while the centre resizes to fill the remainder.
In short, this isn't an ideal solution. All layouting in Swing is made all the more complex by the fact that different components behave in different ways, so you really need to provide further details of the child components you wish to add to your panel, and any behaviour that has been overridden on those components.
The best way is to try a couple of simple examples to see what mileage you get and whether subtle redesign of your child component nesting could help.
you can use a layout, like GridBagLayout, or BorderLayout depending on the situation. With proper weights it is possible.
this sounds to me like you should just peek an appropriate layout manager and use it. For example, look at BorderLayout - put your component in the CENTER and it will occupy all the area. Its up to each concrete layout manager to decide what will be the size of the components.
Mark
I was using a JInternalFrame inside JDesktopPane. I wanted the internal_frame to auto resize as desktop pane is resized, so I had to implement the AncestorResized event for the internal frame where I placed the following code:
this.setPreferredSize(this.getParent().getPreferredSize());
this.pack();

add()ing to a JPanel breaks its size

I have a JPanel identified by myPanel. I create a series of JButtons, and add() them to myPanel. At the end of my generating-and-adding loop, I call myPanel.validate(). The buttons show up.
The problem is the size of the panel is affected. No matter what Layout Manager I choose, the buttons are always added on the same line (even though there is more space beneath them).
I have tried setting myPanel's maximum size and setting its size after every add(). No matter what I do, after that validate(), the panel is blown up and my application's GUI is screwed.
Any ideas?
I create a series of JButtons, and add() them to myPanel... the buttons are always added on the same line (even though there is more space beneath them).
None of the default layout managers provide automatic wrapping. You need to specify how you want wrapping to occur. A GridLayout or a GridBagLayout can be used in these cases.
Or you can try the Wrap Layout which was written for this purpose.
i would firstly set a preferred size on the jpanel:
myPanel.setPreferredSize(new Dimension(X, Y));
this will tell your layout manager how to try to fit the contents within this dimension.
without seeing your source code, i can't add much more than that.

Question to pack() method

I'm building a GUI application, and within a JFrame i have 2 jcombobox's and a JPanel to view certain data. Now when i call the pack() methode in the main class it puts the two jcombobox'es next to my JPanel, which i dont want, because I want them North. Ofcourse I've tried to hard-code it in my code, but it doesn't work after I've called the pack() method.
Are there any alternatives to this method?
Only one component can be NORTH, so if you want both ComboBoxes to be NORTH you have to add them into a separate container. This separate container can then be put NORTH.
(Post the source for more exact help.)
All pack does is resize the Window (in this case JFrame) to its preferred size and the preferred sizes of its sub-components. To control the actual location of the sub-components relative to one another you need to use an appropriate LayoutManager.
You might want to check out the Using Layout Managers tutorial.
The pack() method just causes the layouting to happen, it has abolutely nothing to do with what is put where.
Most likely you're not using layout managers correctly. Show us your code and we can tell you waht exactly you're doing wrong.
You can avoid using pack by explicitly setting the frame size with setSize and setBounds. However, using pack is usually the preferred way as it leaves the frame layout manager in charge of the frame size.
That being said, the problem you are describing appears to be related to the correct use of a layout manager rather than the sizing of the frame. Have a look at the various layout managers for Swing and how to use them: http://download.oracle.com/docs/cd/E17409_01/javase/tutorial/uiswing/layout/using.html.

How to find out the preferred size of a JPanel which is not displayed, according to its content?

I am using a JPanel (with several labels inside) to add a dynamic information on a graph. This panel is dynamically created, it is not visible before I use it to draw.
For this, I am using a BufferedImage, and I follow approximately the same steps as described on this other question. It works good, as long as I specify all sizes (the panel, and its components).
Like asked as well in comments of the referred question, how can I determine the optimal size of this panel? The same operation would be done if this panel was displayed in a regular frame/layout setting.
In my case, how can I "pack", in a way, this panel, so that its size, and size of its content are set to the optimal (determined by the size of labels, then)?
Suraj and willcodejavaforfood put me on the good track.
Checking what is actually done in a pack() method, I see that this is mostly setting the current size to the one returned by getPreferredSize().
From this, I managed to make such solution:
// Creating the panel
JPanel lPanel = new JPanel();
//lPanel.setSize(1000, 1000); //default size, not needed anymore
lPanel.setLayout(new BoxLayout(lPanel, BoxLayout.PAGE_AXIS));
//Adding the content
lPanel.add(new JLabel("Blah"));
// etc...
//Adjust the panel to its preferred size
lPanel.setSize(lPanel.getPreferredSize());
//Call the layout method
//(this will adjust the content components to their correct size and position)
lPanel.doLayout();
This method works correctly, and adjusts the panel and its content to the correct size (and answers my question in a simplistic way: "how to find the preferred size? getPreferredSize()").
However, it requires to set the initial size to a large enough size, so that the content fits in, or they won't be put on the layout. This is a bit pity, and not really "clean", but I can't find a way to avoid that, for now.
Edit: Actually, the default size was not necessary, because getPreferredSize() returns the correct value, even before calling doLayout(). As such, the panel can be set to its proper size before calling the layout method.
The direct answer is to call Window#pack(). This method will automatically set the size of all underlying children to thier preferred sizes(ofcourse this depends on layouts of child containers, for e.g. BorderLayout doesent give a damn about preffered sizes).
So as long as you have set preferred sizes(or min/max sizes in case layouts are like BorderLayout) of your child components, pack() method will be all you need.
[UPDATE]One way is to do is add a HierarchyListener to your jpanel and check for HierarchyEvent#DISPLAYABILITY_CHANGED events. This event is called when your panel is realized that is ready to be shown(and a parent is available), at this moment you can do:
SwingUtilities#getWindowAncestor(myPanel).pack();

Categories