Sunday, July 01, 2012

Java GUI Tutorial 6 - JPanel as a Container

JPanel as a Container

In this tutorial, a new class (extension of JPanel), has been added to the source files and is going to act as a common container for all instances of the ButtonPanel we create. The ButtonPanels are able to operate independently of one another.

The Source Codes for the Tutorial source code is in the code box below this paragraph. The rest of the classes:, and can be found in the last Java GUI tutorial #5. Click here to open the last tutorial

import java.awt.Dimension;

import javax.swing.JFrame;

/** Coded and designed by Brian R. H. 

public class Runner {
 public static void main(String[] args) {
  //where the program begins
  Dimension d = new Dimension(600,400);
  JFrame frame = new JFrame("W7R Java GUI Tutorail #6");
  MainPanel mainPanel = new MainPanel(d);
IMPORTANT: was updated for this tutorial. The version of from tutorial 5 WILL NOT WORK the way we need it to for this tutorial.

MainPanel extends JPanel

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;

/** Coded and designed by Brian R. H. 

public class MainPanel extends JPanel implements ActionListener{
 //main panel will store all sub panels.
 ButtonPanel buttonPanel1, buttonPanel2,
 buttonPanel3, buttonPanel4, buttonPanel5;
 MainPanel(Dimension d){
  setBackground(Color.white); //default background
  buttonPanel1 = new ButtonPanel(d);
  buttonPanel2 = new ButtonPanel(d);
  buttonPanel3 = new ButtonPanel(d);
  buttonPanel4 = new ButtonPanel(d);
  buttonPanel5 =  new ButtonPanel(d);

Important Lines Of Code Explained

new ButtonPanel(d)
creates a new instance of the ButtonPanel class with dimensions d.
adds the ButtonPanel to the MainPanel visually.
implements ActionListener
This snippet from the class is not necessary for this tutorial, but is in preparation for Java GUI Tutorial #7.

Things to Note from the GUI

  • All of the ButtonPanels are not the correct dimension (Dimension d) they were passed in their constructor.
  • appears to be the same color as Color.yellow
  • There seems to be a border around each ColorPanel that was added to the MainPanel.

No comments: