Pages

Sunday, July 01, 2012

Java GUI Tutorial 6 - JPanel as a Container

w7r.blogspot.com



JPanel as a Container

In this tutorial, a new class (extension of JPanel), MainPanel.java 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

MainPanel.java source code is in the code box below this paragraph. The rest of the classes: ButtonPanel.java, and ColorButton.java can be found in the last Java GUI tutorial #5. Click here to open the last tutorial

Runner.java

import java.awt.Dimension;

import javax.swing.JFrame;

/** Coded and designed by Brian R. H. 
 *    w7r.blogspot.com
 **/

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);
  frame.add(mainPanel);
  frame.setSize(d);
  frame.setVisible(true);
 }
}
IMPORTANT: Runner.java was updated for this tutorial. The version of Runner.java 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. 
 *    w7r.blogspot.com
 **/

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
  setSize(d);
  buttonPanel1 = new ButtonPanel(d);
  buttonPanel2 = new ButtonPanel(d);
  buttonPanel3 = new ButtonPanel(d);
  buttonPanel4 = new ButtonPanel(d);
  buttonPanel5 =  new ButtonPanel(d);
  this.add(buttonPanel1);
  this.add(buttonPanel2);
  this.add(buttonPanel3);
  this.add(buttonPanel4);
  this.add(buttonPanel5);
 }
}



Important Lines Of Code Explained

new ButtonPanel(d)
creates a new instance of the ButtonPanel class with dimensions d.
this.add(buttonPanel1)
adds the ButtonPanel to the MainPanel visually.
implements ActionListener
This snippet from the MainPanel.java 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.
  • Color.orange 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:

Post a Comment