Using a ContentPane's JComponent functionality - java

Fred Swartz writes in a note on Java GUI programming (more specifically, about the best ways to access and use a component's ContentPane)
... if we get the predefined content pane [by invoking
getContentPane() on a JFrame], it turns out it's actually a
JPanel, but we really can't take advantage of the functionality that
was added by JComponent.
-- http://www.fredosaurus.com/JavaBasics/gui/gui-commentary/guicom-60-contentpane.html
In this case, what prohibits someone from using the JComponent functionality of a JPanel? JPanel extends JComponent, so shouldn't JPanel have unhindered access to JComponent's methods?

Read further in his comments about using the returned Component:
If we downcast it to JPanel, we create fragile code that might break because the contract with getContentPane() is to return a Container, and there is no guarantee that future versions will actually continue to return a JPanel.

Related

Why can I not call add() on a JFrame and instead must call it on a Container?

I am reading Head First Java. When introducing GUIs (page 354 for those of you who have the book), the author writes:
frame.getContentPane().add(button);
"You don't add things to the frame directly. Think of the frame as the trim around the window, and you add things to the window pane."
After looking at the Java API entry for JFrame, I saw that JFrame is a subclass of Component and inherits the add(Component) from Component, so it would work to simply write:
frame.add(button);
Why does the book recommend to use frame.getContentPane.add(button)?
Thanks in advance!
You can call add(...) on the JFrame, but what it does is in fact call getContentPane().add(...) as per the JFrame API and otherwise known as "syntactic sugar". But understand that in doing this, you aren't in fact adding it directly to the JFrame but in fact are adding it to the contentPane. This is important since the JFrame is made of a composition of components as the JFrame/top level window Swing Tutorial well explains.
Myself, I prefer the literal getContentPane().add(...) because not all JFrame behaviors will work this way, such as setBackground(...), and so being literal reminds me exactly what I am doing.

The JPanel contentpane confusion

I am learning Java Swing and I appended a menuBar to the frame. By default this should call jframe.getContentPane().add(child). When I ran the script the menuBar didn't show up. But the button was at the very top "y=0" if that makes sense.
Then I realized my mistake I actually had to put in a menu in the menubar. Then the menuBar showed up. So that got me thinking...is the "menubar" "contentpane" actually 2 panels? It is confusing the hell out of me. Because that acted a lot like a panel. But getContentPane() returns a Container, not a JPanel object so I'm confused.
If so, does that mean that the only thing that is dumped directly into a frame are just Jpanel objects? Hence JButtons, JLabels are not directly in a frame...
Does that mean, jpanels are "nested"?
One more thing that is confusing me. If a jpanel can control how things are positioned, what is a LayoutManager for? :S
Thanks, and please answer as if to a 2yr old asking why the sky is blue,ha ;)
Some random thoughts:
Yes, JPanels and other components are often "nested". This is where a firm understanding of the Swing/AWT layout managers is essential.
While the type returned by a JFrame's getContentPane() is technically a Container, it's also a JPanel (which inherits eventually from Container).
I believe that you can make anything that derives from Container the contentPane, but you need to take care that it is opaque.
for that there is method
frame.setJMenuBar(menuBar);
for todays Java Swing GUI, is not neccesary declare ContentPane, from Java5, and with BorderLayout as default LayoutManager
then frame.add(myPanel);
//is same as frame.add(myPanel, BorderLayout.CENTER) and occupated whole Container
basic stuff about how to use LayourManagers
getContentPane() always returns a Container instance. However, you should note that JPanel objects are Container instances, as well as other classes in the Swing framework. The actual class of the instance returned is irrelevant, as you do not have control over which implementation of Container is used as a contentPane (unless you have forced a specific contentPane), and most of the time this should not be a problem.
You can add many GUI widgets in a JFrame, such as JButton, JLabel, etc. However, they will be automatically added to the associated contentPane.
JPanel does not handle the objects positioning, the LayoutManager associated with your panel does; either automatically based on its own set of rules (e.g. FlowLayout), or by using the constraints you have specified when adding the object to the container (the GridBagLayout layout manager is a good example). The JavaDoc on the LayoutManagers usually contain enough information to get you started on using them.
You can have nested panels, yes. A Container can contain other Container instances. While it seems to be a complicated solution, it does enable you to control exactly how your GUI is displayed. Depending on which LayoutManager you are using, on the needs you have to fulfill with your user interface, and on your own preferences/habits as a developper, you might need less or more nested panels.
You need to see this API doc for JComponent.
If you look at the inheritance hierarchy, you will see that the JComponent extends Component so a JComponent is a Component.
Also under Direct Known Subclasses, you can see the list of all the classes that extend the JComponent including JMenuBar and JPanel.
So, JMenuBar and JPanel are two more specialized versions of JComponent (or Container).

Prevent Java from repainting the content of a JPanel while updating

I have a JPanel which contains a lot of child components. While updating\adding new components to the parent JPanel I'd like to prevent it from repainting, how can this achieved?
Try RepaintManager.currentManager(component).markCompletelyClean(component). It will prevent the component from repainting. You might need to do this after each time you add new components.
setVisible(false)
update
setVisible(true)
you could try by using setIgnoreRepaint(boolean value) but it's a typical swing feature that can or cannot work (mainly because it depends from AWT so you never know).
Otherwise you could override the paint method by using a flag that simply makes the methor return without calling super.paint(). (actually overriding paintComponent should be the right choice)

Swing: "thin" standard component to act as a container?

I need to pick a standard container (JPanel?) in Swing that I can use as a placeholder to which I can add another custom component that extends JPanel:
JPanel containerPanel;
// built by a library from a text file, automatically part of a nice layout
MyPanel componentPanel;
// something complicated that I can't integrate with the builder library
containerPanel = builder.getMyContainerPanel();
componentPanel = new MyPanel(...);
containerPanel.add(componentPanel);
Is there a way to somehow couple the two panel sizes so that resizing works properly? I'm not quite sure how resizing works in swing, but what I want is for the outer containerPanel to be a thin wrapper that is subservient to my componentPanel and the outer panel delegates as much as possible to the inner panel.
I don't want to do things this way but it seems like the best way to decouple the builder library from my custom component.
I'd simply use a GridLayout.
containerPanel.setLayout(new GridLayout(1, 1));
This has the advantage that you can just add the sub panel without any parameters and it is guaranteed to use the entire area:
containerPanel.add(componentPanel);
You can use a BorderLayout and add your delegate container in the BorderLayout.CENTER position.
Hmm. Well, I decided to rewrite my component, so instead of a class that extends JPanel (inheritance), it uses composition and is constructed with an empty JPanel as a parameter + it adds child components to the JPanel. So I can use the builder library to build the empty JPanel, then later I pass that into my own component's constructor, so now I have 1 JPanel instead of two of them that I have to keep coupled together.

Best way of subclassing a JPanel in Swing

I am currently trying to build an expanding panel in Swing (akin the WPF's Expander control) and I'd like to retain the usual methods for manipulating it (i. e. setLayout, add, etc.). Only they should be routed to an embedded panel (the one being shown or hidden).
How would one do that? Overriding every method of JComponent and re-routing that to an embedded JPanel would be cumbersome, but that's the only way I see.
Or should I rather make the embedded panel visible to the outside and force users to use something like ExpanderPanel.getInnerPanel() instead. But then it's no drop-in replacement for JPanel which I think would be nice to have.
Take a look at the JXTaskPane from Swingx project. It already does what you need.
In 1.5(ish) Swing routed a few methods to the content pane in JFrame, JApplet, etc. Whilst there appeared to be some usability benefits for those just starting, it doesn't actually fix the problem. So everyone has to deal with a very strangely behaving API. So my advice is to avoid this approach.
If you have a Container widget which holds a panel you want to show and hide, why not layout your inner panel however you want, then add it to the Container panel, then use static methods against the Container to say
JPanel p = new JPanel();
//do something with the JPanel...
ContainerWidget.setContent(p);
ContainerWidget.expandPanel(p,true);
Would somethign like this work?

Categories