I l@ve RuBoard |
![]() ![]() |
8.1 A Simple ContainerNot everything in this chapter is more complex than its AWT counterpart. As proof of this claim, we'll start the chapter with a look at the JPanel class, a very simple Swing container. 8.1.1 The JPanel ClassJPanel is an extension of JComponent (which, remember, extends java.awt.Container) used for grouping together other components. It gets most of its implementation from its superclasses. Typically, using JPanel amounts to instantiating it, setting a layout manager (this can be set in the constructor and defaults to a FlowLayout), and adding components to it using the add( ) methods inherited from Container. 8.1.1.1 PropertiesJPanel does not define any new properties. Table 8-1 shows the default values that differ from those provided by JComponent.
The doubleBuffered and opaque properties default to true, while the layoutManager defaults to a new FlowLayout. 8.1.1.2 Constructors
8.1.1.3 OpacityHere's a simple program showing what it means for a JPanel to be opaque. All we do is create a few JPanels. Inside the first JPanel, we place another JPanel, which is opaque. In the second, we place a transparent (nonopaque) JPanel. In both cases, we set the background of the outer panel to white and the background of the inner panel to black. We'll place a JButton inside each inner panel to give it some size. Figure 8-1 shows the result. Figure 8-1. Opaque and nonopaque JPanels (in Metal and Mac L&Fs)![]() On the left, we see the black panel inside the white one. But on the right, since the inner panel is not opaque, its black background is never painted, and the background of the outer panel shows through. Here's the code: // OpaqueExample.java // import javax.swing.*; import java.awt.*; public class OpaqueExample extends JFrame { public OpaqueExample( ) { super("Opaque JPanel Demo"); setSize(400, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); // Create two JPanels (opaque), one containing another opaque JPanel and the // other containing a nonopaque JPanel. JPanel opaque = createNested(true); JPanel notOpaque = createNested(false); // Throw it all together. getContentPane( ).setLayout(new FlowLayout( )); getContentPane( ).add(opaque); getContentPane( ).add(notOpaque); } public static void main(String[] args) { OpaqueExample oe = new OpaqueExample( ); oe.setVisible(true); } // Create a JPanel containing another JPanel. The inner JPanel's opacity is set // according to the parameter. A JButton is placed inside the inner JPanel to give // it some content. public JPanel createNested(boolean opaque) { JPanel outer = new JPanel(new FlowLayout( )); JPanel inner = new JPanel(new FlowLayout( )); outer.setBackground(Color.white); inner.setBackground(Color.black); inner.setOpaque(opaque); inner.setBorder(BorderFactory.createLineBorder(Color.gray)); inner.add(new JButton("Button")); outer.add(inner); return outer; } } |
I l@ve RuBoard |
![]() ![]() |