frame.pack()

Download Report

Transcript frame.pack()

Java Swing Components and
Containment
1
Components and Containers

Components
• The building blocks
• Variety of uses and complexities

Containers
• The cement
• Hierarchical organisation
• Distinction is not always drawn
2
Containment hierarchies

Top level containers
• Intermediate containers


Atomic components
Viewing containment hierarchies
• <Ctrl-Shift-F1>
3
Top-level containers




At the root of every containment
hierarchy
All Swing programs have at least one
Content panes
Types of top-level containers
• Frames
• Dialogs
• Applets
4
Using Top-Level Containers



To appear onscreen, every GUI
component must be part of a
containment hierarchy.
A containment hierarchy is a tree of
components that has a top-level
container as its root.
We'll show you one in a bit.
5
Using Top-Level Containers


Each GUI component can be contained
only once.
If a component is already in a container
and you try to add it to another
container, the component will be
removed from the first container and
then added to the second.
6
Using Top-Level Containers

Each top-level container has a
content pane that, generally
speaking, contains (directly or
indirectly) the visible components
in that top-level container's GUI.
7
Using Top-Level Containers



You can optionally add a menu bar to a toplevel container.
The menu bar is by convention positioned
within the top-level container, but outside the
content pane.
Some look and feels, such as the Mac OS look
and feel, give you the option of placing the
menu bar in another place more appropriate
for the look and feel, such as at the top of the
screen.
8
Using Top-Level Containers
9
Using Top-Level Containers
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
10
Using Top-Level Containers
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
11
Using Top-Level Containers
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
12
Using Top-Level Containers
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel,
BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
13
Using Top-Level Containers
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
14
Using Top-Level Containers
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* TopLevelDemo.java requires no other files. */
public class TopLevelDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TopLevelDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.
JMenuBar greenMenuBar = new JMenuBar();
greenMenuBar.setOpaque(true);
greenMenuBar.setBackground(new Color(154, 165, 127));
greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.
JLabel yellowLabel = new JLabel();
yellowLabel.setOpaque(true);
yellowLabel.setBackground(new Color(248, 213, 131));
yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.
frame.setJMenuBar(greenMenuBar);
frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
15
Frames

Window with border, title and buttons

Making frames
• JFrame frame = new JFrame();
Or extend JFrame class (often better code this way).

Style defined with
UIManager.setLookAndFeel(looknfeel);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
16
a JFrame example
//this won’t compile…
public static void main(String[] args)
{
JFrame frame = new JFrame(“A JFrame"); //Just like
any
//other
class
// do things with frame
frame.setJMenuBar(menuBar);
frame.setContentPane(contentPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set frame size
frame.pack();
// realize frame
frame.setVisible(true);
} // end main
17
a JFrame example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
}
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
18
a JFrame example
Adding Components to
the Content Pane.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel,
BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
19
a JFrame example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
}
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
20
a JFrame example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* FrameDemo.java requires no other files. */
public class FrameDemo {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
}
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
21
}
}
});
Examples 1 + 2

SwingApplication.java
• Messy way.

BetterSwingApp.java
• Neater way.
22
Examples 1
//--//--//--//--//---
SwingApplication.java
This is a poor example of how to make a window appear.
It clearly illustrates what is happening, but does not scale well.
The next example improves upon the design.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingApplication {
public Component createComponents() {
final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW");
/*
* An easy way to put space between a top-level container
* and its contents is to put the contents in a JPanel
* that has an "empty" border.
*/
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(
pane.add(label);
}
30, //top
30, //left
10, //bottom
30) //right
);
return pane;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e)
{}
23
Examples 1
//--//--//--//--//---
SwingApplication.java
This is a poor example of how to make a window appear.
It clearly illustrates what is happening, but does not scale well.
The next example improves upon the design.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingApplication {
public Component createComponents() {
final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW");
/*
* An easy way to put space between a top-level container
* and its contents is to put the contents in a JPanel
* that has an "empty" border.
*/
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);
24
Examples 1
//--//--//--//--//---
SwingApplication.java
This is a poor example of how to make a window appear.
It clearly illustrates what is happening, but does not scale well.
The next example improves upon the design.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e)
{}
//Create the top-level container and
JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class
SwingApplication app = new SwingApplication();
//Create the components
Component contents = app.createComponents();
//Create new Jpanel for content pane
JPanel contentPane = new JPanel();
//add them to the content pane of the main frame
contentPane.add(contents);
//Make new panel the content pane
//
contentPane.setOpaque(true);
frame.setContentPane(contentPane);
//enable the frame to close.
25
Examples 1
//--//--//--//--//---
SwingApplication.java
This is a poor example of how to make a window appear.
It clearly illustrates what is happening, but does not scale well.
The next example improves upon the design.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e)
{}
//Create the top-level container and
JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class
SwingApplication app = new SwingApplication();
//Create the components
Component contents = app.createComponents();
//Create new Jpanel for content pane
JPanel contentPane = new JPanel();
//add them to the content pane of the main frame
contentPane.add(contents);
//Make new panel the content pane
26
Examples 1
//--//--//--//--//---
SwingApplication.java
This is a poor example of how to make a window appear.
It clearly illustrates what is happening, but does not scale well.
The next example improves upon the design.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e)
{}
//Create the top-level container and
JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class
SwingApplication app = new SwingApplication();
//Create the components
Component contents = app.createComponents();
//Create new Jpanel for content pane
JPanel contentPane = new JPanel();
//add them to the content pane of the main frame
contentPane.add(contents);
//Make new panel the content pane
//
contentPane.setOpaque(true);
frame.setContentPane(contentPane);
//enable the frame to close.
27
Examples 1
//--//--//--//--//---
SwingApplication.java
This is a poor example of how to make a window appear.
It clearly illustrates what is happening, but does not scale well.
The next example improves upon the design.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public static void main(String[] args) {
try {
//Make new panel the content pane
//
contentPane.setOpaque(true);
frame.setContentPane(contentPane);
//enable the frame to close.
//NOTE - This is the old way, but included as an example of
//
- code you may see on the web
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
28
Examples 2
// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SwingExample extends JFrame
implements ActionListener
{
// declare variables
static JPanel contentPane;
static JMenuBar menuBar;
static JMenu fileMenu;
JMenuItem menuItem;
JButton helloButton;
JButton goodbyeButton;
JLabel label;
BorderLayout borderLayout;
public SwingExample(String title)
{
//Set title - passed in the constructor
setTitle(title);
//enable to close - The new way
setDefaultCloseOperation(EXIT_ON_CLOSE);
// set up menu bar
29
Examples 2
// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SwingExample extends JFrame
implements ActionListener
{
public SwingExample(String title)
{
//Set title - passed in the constructor
setTitle(title);
//enable to close - The new way
setDefaultCloseOperation(EXIT_ON_CLOSE);
// set up menu bar
menuBar = new JMenuBar();
menuBar.setLayout(new BoxLayout(menuBar,
BoxLayout.X_AXIS));
fileMenu = new JMenu("File");
menuBar.add(fileMenu);
menuItem = new JMenuItem("Exit");
30
import
import
import
import
javax.swing.*;
javax.swing.event.*;
java.awt.*;
java.awt.event.*;
public class SwingExample extends JFrame
implements ActionListener
{
Examples
2
// set up label
label = new JLabel("Hello");
label.setHorizontalAlignment(JLabel.CENTER);
// set up buttons
helloButton = new JButton("Hello");
helloButton.setActionCommand("Hi");
helloButton.addActionListener(this);
goodbyeButton = new JButton("Goodbye");
goodbyeButton.setActionCommand("Bye");
goodbyeButton.addActionListener(this);
//set up layout - not worry about now
borderLayout = new BorderLayout();
borderLayout.setHgap(5);
borderLayout.setVgap(10);
// set layout of content pane
getContentPane().setLayout(borderLayout);
//add the contents
getContentPane().add(label, BorderLayout.NORTH);
31
Examples 2
// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class SwingExample extends JFrame
implements ActionListener
{
//add the contents
getContentPane().add(label, BorderLayout.NORTH);
getContentPane().add(helloButton, BorderLayout.EAST);
getContentPane().add(goodbyeButton, BorderLayout.WEST);
//--- Now in 1.5 we can just use add() directly
//--//add(label, BorderLayout.NORTH);
//add(helloButton, BorderLayout.EAST);
//add(goodbyeButton, BorderLayout.WEST);
} // end constructor
//Message handlers - don't worry too much at this stage.
public void actionPerformed(ActionEvent e)
{
if ((e.getActionCommand()).equals("Exit"))
32
Examples 2
//Message handlers - don't worry too much at this stage.
public void actionPerformed(ActionEvent e)
{
if ((e.getActionCommand()).equals("Exit"))
{
System.exit(0);
}
else if ((e.getActionCommand()).equals("Hi"))
{
label.setText("Hello");
}
else if ((e.getActionCommand()).equals("Bye"))
{
label.setText("Goodbye");
}
} // end actionPerformed
//Where it all begins - the main method
public static void main(String[] args)
{
//create instance of this class
SwingExample example = new SwingExample("Swing Example");
33
Examples 2
//Where it all begins - the main method
public static void main(String[] args)
{
//create instance of this class
SwingExample example = new
SwingExample("Swing Example");
//layout and display the JFrame & its contents
example.pack();
example.setVisible(true);
} // end main
} // end class Swing example
34
Dialog boxes



More limited than frames
Modality
Types of dialogs
•
•
•
•
JOptionPane
ProgressMonitor
JColorChooser
JDialog
35
Showing dialogs

JOptionPane.showXYZDialog(…)
• Option and Message dialogs
JOptionPane.showMessageDialog(frame, ”Error!”, ”An error
message”, JOptionPane.ERROR_MESSAGE);
JOptionPane.showOptionDialog(frame, “Save?”, “A save
dialog”, JOptionPane.YES_NO_CANCEL_OPTION);
• Input, Confirm

Customisation
• showOptionDialog - Fairly customisable
• JDialog - Totally customisable
36
Showing dialogs
JOptionPane.showMessageDialog(frame, "Eggs are
not supposed to be green.");
37
Example 3

DialogDemo.java
• Not looking at code in detail…
38
Example 3
//default icon, custom title
int n = JOptionPane.showConfirmDialog( frame, "Would you like green eggs
and ham?", "An Inane Question", JOptionPane.YES_NO_OPTION);
Object[] options = {"Yes, please", "No way!"}; int n =
JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?",
"A Silly Question", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, //do not use a custom Icon options,
//the titles of buttons options[0]); //default button title
39
Applets

Not covered in great detail here

JApplet is a top-level container
• has menu bar and content pane support


JApplet supports assistive
technologies
Requires Java plug-in for browser
• consider user group
40
Intermediate containers –
Panels (or ‘panes’)

Root panes
• The content pane
• Layered panes
• Glass panes
• optional menu bar
41
Intermediate containers –
Panels (or ‘panes’)

You get a JRootPane
(whether you want it or not!)
The content pane
when you instantiate
Layered panes
JInternalFrame or one of the
top-level Swing containers,
Glass panes
such as JApplet, JDialog, and
optional menu bar
JFrame.
Root panes
•
•
•
•
42
Root panes

‘Invisibly’ attached to top-level container

Created by Swing on realizing frame


Manages everything between top-level container
and components
Places menu bar and content pane in an instance
of JLayeredPane (see a couple of slides on)
43
Content panes



Usually use a JPanel
Contains everything except menu bar for most
Swing applications
Can be explicitly, or
implicitly created,
• see (simplified) code
//Create a panel and add components to it.
JPanel contentPane = new JPanel();
contentPane.add(someComponent);
contentPane.add(anotherComponet);
//Make it the content pane.
contentPane.setOpaque(true);
topLevelContainer.setContentPane(contentPane);
44
Example 4

TopLevelDemo.java
• Illustrates the Content Pane, and
Menu Bar positioning (see slides 10
-15).
45
Layered panes



Provided by root pane, but can also be
created
Provides depth (z-buffering) to
components
‘Depth’ is specified as integer
•
•
•
•
•
•
Frame content (-30000, content pane, menu bar)
Default (0, components)
Palette (100, toolbars and palettes)
Modal (200, internal dialogs)
Popup (300, external dialogs)
Drag (400, component when dragged)
46
Layered panes
Provided by root pane, but can also be
created
overlapping
components
 Provides
depth
can
appear
one (z-buffering)
on top of to
components
the other
 How
‘Depth’
specified
as integer
toisuse
toot pane

•
•
•
•
•
•
Frame content (-30000, content pane, menu bar)
Default (0, components)
Palette (100, toolbars and palettes)
Modal (200, internal dialogs)
Popup (300, external dialogs)
Drag (400, component when dragged)
47
Example 5

LayeredPaneDemo.java
48
Example 5
import javax.swing.*;
import javax.swing.border.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
public class LayeredPaneDemo extends JFrame {
private String[] layerStrings = { "Yellow (0)", "Magenta (1)",
"Cyan (2)", "Red (3)",
"Green (4)" };
private Color[] layerColors = { Color.yellow, Color.magenta,
Color.cyan, Color.red,
Color.green };
private JLayeredPane layeredPane;
private JLabel dukeLabel;
public LayeredPaneDemo() {
super("LayeredPaneDemo");
//Create and load the duke icon.
final ImageIcon icon = new ImageIcon("duke.gif");
//Create and set up the layered pane.
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(300, 310));
layeredPane.setBorder(BorderFactory.createTitledBorder(
"Move the Mouse to Move Duke"));
layeredPane.addMouseMotionListener(new MouseMotionAdapter() {
final int XFUDGE = 40;
final int YFUDGE = 57;
public void mouseEntered(MouseEvent e) {
dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);
}
public void mouseMoved(MouseEvent e) {
dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);
}
});
//This is the origin of the first label added.
Point origin = new Point(10, 20);
49
Example 5
//Create and set up the layered pane.
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(300, 310));
layeredPane.setBorder(BorderFactory.createTitledBorder(
"Move the Mouse to Move Duke"));
layeredPane.addMouseMotionListener(new
MouseMotionAdapter() {
final int XFUDGE = 40;
final int YFUDGE = 57;
public void mouseEntered(MouseEvent e) {
dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()YFUDGE);
}
public void mouseMoved(MouseEvent e) {
dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()YFUDGE);
}
});
50
Example 5
//Create and add the Duke label to the layered pane.
dukeLabel = new JLabel(icon);
dukeLabel.setBounds(15, 225,
icon.getIconWidth(),
icon.getIconHeight());
layeredPane.add(dukeLabel, new Integer(2), 0);
}
//Add control pane and layered pane to frame.
Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane,
BoxLayout.Y_AXIS));
contentPane.add(Box.createRigidArea(new Dimension(0, 10)));
contentPane.add(createControlPanel());
contentPane.add(Box.createRigidArea(new Dimension(0, 10)));
contentPane.add(layeredPane);
51
Example 5
//Create the control pane for the top of the frame.
private JPanel createControlPanel() {
final JCheckBox onTop = new JCheckBox("Top Position in
Layer");
onTop.setSelected(true);
onTop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (onTop.isSelected())
layeredPane.moveToFront(dukeLabel);
else
layeredPane.moveToBack(dukeLabel);
}
});
52
Glass panes

Not structured into components
• event catching
• painting


Used for ‘weird’ interface behavior,
rarely used.
Either created explicitly or root
version used
53
Example 6

GlassPaneDemo.java
54
Example 6



It contains a check box that lets you set
whether the glass pane is "visible" —
whether it can get events and paint itself
onscreen.
When the glass pane is visible, it blocks all
input events from reaching the
components in the content pane.
It also paints a red dot in the place where
it last detected a mouse-pressed event.
55
Components

Content of your interface
• http://java.sun.com/docs/books/tutorial/uiswi
ng/components/components.html

Created just like any class instance
• JButton button_ok = new JButton(“OK”);

Range in complexity from very simple
(e.g. JButton) to very detailed (e.g.
JColorChooser)
56
Swing and AWT components a quick reminder


Mix Swing and AWT components as
little as possible (not at all in most
cases)
Put ‘J’ in front of everything AWT
provides to get Swing’s counterpart
• AWT: Button
• Swing: JButton
57
Atomic components







Buttons
Combo boxes
Lists
Menus
Sliders
Text Fields
Labels
58
Atomic components







Tool tips
Progress bars
Colour choosers
File choosers
Tables
Text
Trees
59
Atomic components



Impossible to teach the working of every type of
component
Very few people know it all! – Swing is HUGE.
Remember to refer to:
• Swing tutorial
• The Java 2 API Documentation.
• The Visual index to components & containers at
java.sun.com:

http://java.sun.com/docs/books/tutorial/uiswing/components/com
ponents.html
60
Summary

Containers (Frames and Dialogs)
•
•
•
•
•

Hierarchy
Root Panes
Layered Panes
Content Panes
Glass Panes
Components
• Lots of ‘em…

Next time
• Layout Management.
61