
LAB 40 – GUI (Frames and Panels)
Lab Exercises
Topics
To introduce components and containers used in graphical user interfaces.
To write a GUI using frames and panels
To use the BlueJ IDE to write and test the application
Using BlueJ to start a new application
1) Starting BlueJ - double-click icon.
2) Creating a new project - select New Project from the Project menu and save the project as GUI.
3) Click on New Class and type NestedPanels as the class name and select Class as the class type
4) Right-click on the NestedPanels class and select Open Editor
5) Review the default code generated by BlueJ.
6) Replace the code generated by BlueJ with the following; update the comments.
//********************************************************************
// NestedPanels.java Author: Lewis/Loftus
//
// Demonstrates a basic component hierarchy.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class NestedPanels
{
//-----------------------------------------------------------------
// Presents two colored panels nested within a third.
//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("Nested Panels");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Set up first subpanel
JPanel subPanel1 = new JPanel();
subPanel1.setPreferredSize (new Dimension(150, 100));
subPanel1.setBackground (Color.green);
JLabel label1 = new JLabel ("One");
subPanel1.add (label1);
// Set up second subpanel
JPanel subPanel2 = new JPanel();
subPanel2.setPreferredSize (new Dimension(150, 100));
subPanel2.setBackground (Color.red);
JLabel label2 = new JLabel ("Two");
subPanel2.add (label2);
// Set up primary panel
JPanel primary = new JPanel();
primary.setBackground (Color.blue);
primary.add (subPanel1);