JPanels

What is a JPanel?

A JPanel is a container class that allows components to be added to it.  Remember that Science Fair Display Board?  Each section for the science fair project board is set apart with a heading and details on the project, like the “Materials”, “Results” or “Procedure” section.  Compare a JPanel to each of those sections.  A JPanel will group the components your program needs to function and treat them as one unit.

JPanels fall into a ‘view’ component in the Model-View-Controller design pattern <<ADD MORE DETAILS HERE AND INCLUDE AN IMAGE>>

In order to keep our project organized, create two additional packages – model and view.  

JPanels will be defined in their own classes to keep the functionality separate.  Inside the view package, create a new class called MadLibForm.  This class needs to be treated as a JPanel so have it extend from JPanel in order for it to be a JPanel (remember from inheritance the IS-A relationship – MadLibFrom IS-A JPanel).

package view;

import javax.swing.JPanel;

public class MadLibForm extends JPanel{

}

Should we talk about the serial id now or later?  Your IDE might be trying to alert you to an issue.

The serializable class does not declare a static final serialVersionUID field of type long

Serialization is what you do to an instance of an object if you want to dump it to a raw buffer, save it to disk, transport it in a binary stream (e.g., sending an object over a network socket), or otherwise create a serialized binary representation of an object. If you have no intention of serializing your class, you can add the annotation just above your class @SuppressWarnings(“serial”).

Add @SuppressWarnings 'serial' to
@SuppressWarnings("serial")
public class MadLibForm extends JPanel{

}

Displaying the JPanel

Before we start adding components to the JPanel, let’s get the JPanel to display on the frame.  By adding it right away, we will be able to see our changes to the application when running it immediately.

Returning back to the StartProgram.java file, delete the dueling buttons and add an instance of the JPanel we just created.  Add it to the JFrame.  Also, change the title to be more descriptive.  The final code looks like:

JFrame frame = new JFrame();
 frame.setSize(300, 300);
 
 frame.setTitle("Create a MadLib");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
 MadLibForm panel = new MadLibForm();
 frame.add(panel);
 
 frame.setVisible(true);
 
 }

First, we create the instance of the JPanel.  Finally, add it to the JFrame by using the .add( ) method from the JFrame class.  Running the program now will reflect in the buttons removed, an empty frame and a new title. <<INSERT IMAGE>>

Adding Items to the JPanel

The Java Swing has all kinds of components we can add to our JPanel.

The process for using these components are:

  1. Declaring the component
  2. Importing the package of the component
  3. Initialize the component using the constructor
  4. Adding the component to the JPanel

Recall that when an object is created, the first item called is the constructor.  Inside the constructor, we can add all the components that our panel needs for the program.  This includes all text areas, buttons, graphics, etc.  There are multiple approaches to adding these components.  Some developers will create them in the default no-arg constructor.  Some will create a method to add the components and then call the method in the constructor.  For this demonstration and future program advancements, we will opt to create a separate method and call this method from the constructor.

Create a method that returns void to create the components and add them to the JPanel. 

private void createComponents() {
 
 }

Create a default, no arg constructor inside the MadLibForm class.  Have it call the createComponents( ) method to initialize the components and add them to the panel.

@SuppressWarnings("serial")
public class MadLibForm extends JPanel{
 
 public MadLibForm() {
     createComponents();
 }

}

In Java Swing, components are typically declared to be global variables – available throughout the whole class but private for access only inside the class.  They are typically declared outside of any methods or constructors and initialized when they are created.

Let’s begin by creating a title: MadLib Generator.

  1. Declare the component

“MadLib Generator” is simply text.  Text objects utilize the JLabel object.  Create an instance of the JLabel object at the top of the class, outside constructor or methods, to make it globally available inside the class.

public class MadLibForm extends JPanel{
 private JLabel programTitle;
  1. Importing the package of the component

When you declare the JLabel, you will also have to automatically import the JLabel class from the javax package. 

import javax.swing.JLabel;
  1. Initialize the component using the constructor

At this time, we have a JLabel called programTitle but it has not been initialized or added to the JPanel for display.  Inside the createComponent method, initialize the JLabel to contain our text.  You could also set up a font if you want it to display larger:

private void createComponents() {
 programTitle = new JLabel("MadLib Generator");
 programTitle.setFont(new Font("Sans serif", Font.BOLD, 18));
  1. Adding the component to the JPanel

Add the component to the JPanel using the JPanel add( ) method.  It is built into the JPanel superclass and takes a parameter of the item that you want to add to the panel:

add(programTitle);

The whole MadLibForm JPanel at this point looks like this:

package view;

import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MadLibForm extends JPanel{
 private JLabel programTitle;
 
 public MadLibForm() {
 createComponents();
 }
 
 private void createComponents() {
 programTitle = new JLabel("MadLib Generator");
 programTitle.setFont(new Font("Sans serif", Font.BOLD, 18));
 add(programTitle);
 }

}

When the program runs, the component displays on the JPanel inside the JFrame.

It might look like our panel is fancy since the text is centered but by default, it will take whatever is added to the panel and center it starting at the top.

Let’s add another JLabel to ask for a noun:

  1. Declaring the component
 public class MadLibForm extends JPanel{
 private JLabel programTitle;
 private JLabel nounLabel; 
  1. Importing the package of the component

The JLabel class has already been imported so we do not need to add another one.

  1. Initialize the component using the constructor
 private void createComponents() {
  ....
  nounLabel = new JLabel("Noun: ");
 } 
  1. Adding the component to the JPanel
add(nounLabel);

Objects are added to the JPanel the order they are added in the method.  Since the programTitle label is added before the nounLabel, it will appear first on the panel.  If you wanted the nounLabel to appear first, then it would be added in the createComponents( ) method first.