On the Oracle website, at
Using Top-Level Containers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
I have this paragraph:
However, it does not really give a definition of typecasting, or how it appliesIt's easy to customize the content pane — setting the layout manager or adding
a border, for example. However, there is one tiny gotcha. The getContentPane
method returns a Container object, not a JComponent object. This means that
if you want to take advantage of the content pane's JComponent features, you
need to either typecast the return value or create your own component
to be the content pane. Our examples generally take the second approach,
since it's a little cleaner.
to UI programming, so I am wondering what the heck they are talking about.
The Java API says:
public Container getContentPane()
Returns the contentPane object for this dialog.
So I'm thinking they may be talking about casting
But that is just a shot in the dark.jComponent = (JComponent) getContentPane();
They say it is easier toand say that it is easier, but I have no idea what the hell theycreate your own component to be the content
pane
are talking about . . .
Here is the whole code example they are providing:
import java.awt.*; import javax.swing.*; /* TopLevelDemo.java requires no other files. */ public class TopLevelDemo { /** * Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread. */ private static void createAndShowGUI() { //Create and set up the window. JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 205, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); //Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); //Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); frame.setLocation(700, 400); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }