JPanel - Part 2

JPanels are not only used as a layer for the Content Pane, they are a generic container for widgets and can do all sorts of things. In the next part of this tutorial, we will show you how to add widgets to the Content Pane and teach you basic manipulation of a JPanel.

Now it is time to actually add something to the Window that you can see! "At last!" I hear you yell. This process is very simple. Let's look at the example previously and add some coloured panels to the content pane.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import javax.swing.*;
import java.awt.Color;

public class PanelExample_Extended{
    
     public JPanel createContentPane (){
        
        // We create a bottom JPanel to place everything on.
        JPanel totalGUI = new JPanel();
        
        // We set the Layout Manager to null so we can manually place
        // the Panels.
        totalGUI.setLayout(null);
        
        // Now we create a new panel, size it, shape it,color it red.
        // then add it to the bottom JPanel.
        JPanel redPanel = new JPanel();
        redPanel.setBackground(Color.red);
        redPanel.setLocation(10, 10);
        redPanel.setSize(50,50);
        totalGUI.add(redPanel);

        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        bluePanel.setLocation(220, 10);
        bluePanel.setSize(50, 50);
        totalGUI.add(bluePanel);
        
        // Finally we return the JPanel.
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] There's 3 JPanels in here! [=]");
        
        //Create and set up the content pane.
        PanelExample_Extended demo = new PanelExample_Extended();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(290, 100);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
When run (and please attempt to run this yourself) the screen should look a bit like this...

Picture of Coloured Panels

The only code we have changed is the code within the method of createContentPane().
To start with, we create a JPanel object. This will be the bottom JPanel, the base layer on the GUI that we add things to.
9
        JPanel totalGUI = new JPanel();
JPanels are normally controlled by an interface called the LayoutManager. It helps you quickly place your widgets in a variety of ways, and we cover how to use the LayoutManager later on in the tutorials. For now, I want to place my widgets manually, so I have turned the LayoutManager on the Content Pane off. This is done by setting the layout to null.
13
        totalGUI.setLayout(null);
We create a JPanel object and called it redPanel.
17
        JPanel redPanel = new JPanel();
We change the background colour to red, and give the JPanel a size using setSize(width, height).
We also give the widget a location using setLocation(x pixels, y pixels). This sets the top left hand corner of the widget to the specified position.
For reference, location is set assuming the top left hand corner of the Content Pane is position (0,0).
18
19
20
        redPanel.setBackground(Color.red);
        redPanel.setLocation(10, 10);
        redPanel.setSize(50,50);
To add this to the bottom JPanel, we simply use the syntax add(); If you do not add the widget to the Content Pane, it will not be displayed.
21
        totalGUI.add(redPanel);
We repeated this process again, adding a blue JPanel to the other end of the Content Pane.
23
24
25
26
27
        JPanel bluePanel = new JPanel();
        bluePanel.setBackground(Color.blue);
        bluePanel.setLocation(220, 10);
        bluePanel.setSize(50, 50);
        totalGUI.add(bluePanel);
Finally we set the JPanel to opaque before returning the bottom JPanel so that it can be set as the content pane. This bottom JPanel is re-sized automatically to fit all the widgets positioned on it.
30
31
        totalGUI.setOpaque(true);
        return totalGUI;
So now both JPanels have been added to the bottom JPanel, and the bottom JPanel has been made the Content Pane! Easy peasy. We will use this process to add things to JPanels and the Content Pane throughout the rest of the tutorials.

Several things to note here. JPanels are containers, and you can nest them. If you have a set of widgets that need to be defined in a certain order and stay like that, place them in a JPanel. That way you can move that JPanel around the screen without having to change the order or positioning of the widgets within that JPanel.

Please bear in mind that JPanels should not really be used for drawing on a screen. We colour them here so it's easy for you to get to grips with the main points of positioning and sizing an object. There is a separate Graphics2D package for drawing in Swing that will be covered in a more advanced tutorial.

Exercises

To confirm you know what to do, and to get you thinking, here are three simple exercises to carry out.

1) Colour the bottom JPanel (totalGUI) so you can see its location and size.
2) Set the visibility of the bottom JPanel (totalGUI) to false.
3) Try adding a green and a yellow JPanel to the JFrame.

Hint for Exercise #1
Hint for Exercise #2
Hint for Exercise #3

Exercise #1 Example Code
Exercise #2 Example Code
Exercise #3 Example Code

Questions

Before we move on, answer these simple questions on the JPanel

Question 1. What is the Content Pane used for?

  • a) Giving the page numbers for your documentation.
  • b) Displaying Text, Buttons and other assorted widgets in the Frame.
  • c) Giving you a feeling of well-being while being hurt.

Question 2. How do we add an object called Toaster to the JPanel?

  • a) send.a.Toaster.to.the.JPanel();
  • b) add(Toaster);
  • c) set(Toaster, JPanel);

Question 3. Without being told specifically, how do you think we remove an object called Toaster from the JPanel?

  • a) remove(Toaster);
  • b) KILL(Toaster);
  • c) Use a fork.

Question 4. Where is position 0,0 in the Content Pane?

  • a) Top-right hand corner.
  • b) Top-left hand corner.
  • c) Centre.

Question 5. What are JPanels really good for?

  • a) Drawing complex shapes.
  • b) Acting as buttons.
  • c) Holding widgets in a set pattern so they can be moved together easily.
  • d) Making a GUI look more complicated than it actually is.




You are now wise in the ways of the JPanel. The next tutorial, JLabel, should be simple for you.

Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict