1 Java Swing - Components and Containment. 2 Components and Containers Components and Containers...
-
Upload
joel-goodman -
Category
Documents
-
view
248 -
download
0
Transcript of 1 Java Swing - Components and Containment. 2 Components and Containers Components and Containers...
11
Java Swing - Java Swing - Components and Components and
ContainmentContainment
22
Components and ContainersComponents and Containers
ComponentsComponents• The building blocksThe building blocks• Variety of uses and complexitiesVariety of uses and complexities
ContainersContainers• The cementThe cement• Hierarchical organisationHierarchical organisation• Distinction is not always drawnDistinction is not always drawn
33
Containment hierarchiesContainment hierarchies
Top level containersTop level containers• Intermediate containersIntermediate containers
Atomic componentsAtomic components
Viewing containment hierarchiesViewing containment hierarchies• <Ctrl-Shift-F1><Ctrl-Shift-F1>
44
Top-level containersTop-level containers
At the root of every containment At the root of every containment hierarchyhierarchy
All Swing programs have at least oneAll Swing programs have at least one Content panesContent panes Types of top-level containersTypes of top-level containers
• FramesFrames• DialogsDialogs• AppletsApplets
55
Using Top-Level ContainersUsing Top-Level Containers
To appear onscreen, every GUI To appear onscreen, every GUI component must be part of a component must be part of a containment hierarchy. containment hierarchy.
A containment hierarchy is a tree of A containment hierarchy is a tree of components that has a top-level components that has a top-level container as its root. container as its root.
We'll show you one in a bit. We'll show you one in a bit.
66
Using Top-Level ContainersUsing Top-Level Containers
Each GUI component can be contained Each GUI component can be contained only once. only once.
If a component is already in a container If a component is already in a container and you try to add it to another and you try to add it to another container, the component will be container, the component will be removed from the first container and removed from the first container and then added to the second. then added to the second.
77
Using Top-Level ContainersUsing Top-Level Containers
Each top-level container has a Each top-level container has a content pane that, generally content pane that, generally speaking, contains (directly or speaking, contains (directly or indirectly) the visible components indirectly) the visible components in that top-level container's GUI. in that top-level container's GUI.
88
Using Top-Level ContainersUsing Top-Level Containers
You can optionally add a menu bar to a top-You can optionally add a menu bar to a top-level container. level container.
The menu bar is by convention positioned The menu bar is by convention positioned within the top-level container, but outside the within the top-level container, but outside the content pane. content pane.
Some look and feels, such as the Mac OS look Some look and feels, such as the Mac OS look and feel, give you the option of placing the and feel, give you the option of placing the menu bar in another place more appropriate menu bar in another place more appropriate for the look and feel, such as at the top of the for the look and feel, such as at the top of the screen. screen.
99
Using Top-Level ContainersUsing Top-Level Containers
1010
Using Top-Level ContainersUsing Top-Level Containerspackage components;package components;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* TopLevelDemo.java requires no other files. *//* TopLevelDemo.java requires no other files. */public class TopLevelDemo {public class TopLevelDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/
private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("TopLevelDemo");JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSEframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE););
//Create the menu bar. Make it have a green background.//Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar();JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true);greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127));greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.//Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel();JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true);yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131));yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.//Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar);frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1111
Using Top-Level ContainersUsing Top-Level Containers
package components;package components;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* TopLevelDemo.java requires no other files. *//* TopLevelDemo.java requires no other files. */public class TopLevelDemo {public class TopLevelDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("TopLevelDemo");JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.//Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar();JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true);greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127));greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.//Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel();JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true);yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131));yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.//Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar);frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1212
Using Top-Level ContainersUsing Top-Level Containerspackage components;package components;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* TopLevelDemo.java requires no other files. *//* TopLevelDemo.java requires no other files. */public class TopLevelDemo {public class TopLevelDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("TopLevelDemo");JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.//Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar();JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true);greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127));greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.//Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel();JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true);yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131));yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.//Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar);frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1313
Using Top-Level ContainersUsing Top-Level Containerspackage components;package components;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* TopLevelDemo.java requires no other files. *//* TopLevelDemo.java requires no other files. */public class TopLevelDemo {public class TopLevelDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("TopLevelDemo");JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.//Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar();JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true);greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127));greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.//Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel();JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true);yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131));yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.//Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar);frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1414
Using Top-Level ContainersUsing Top-Level Containerspackage components;package components;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* TopLevelDemo.java requires no other files. *//* TopLevelDemo.java requires no other files. */public class TopLevelDemo {public class TopLevelDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("TopLevelDemo");JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.//Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar();JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true);greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127));greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.//Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel();JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true);yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131));yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.//Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar);frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1515
Using Top-Level ContainersUsing Top-Level Containerspackage components;package components;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* TopLevelDemo.java requires no other files. *//* TopLevelDemo.java requires no other files. */public class TopLevelDemo {public class TopLevelDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("TopLevelDemo");JFrame frame = new JFrame("TopLevelDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create the menu bar. Make it have a green background.//Create the menu bar. Make it have a green background. JMenuBar greenMenuBar = new JMenuBar();JMenuBar greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true);greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127));greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20));greenMenuBar.setPreferredSize(new Dimension(200, 20));
//Create a yellow label to put in the content pane.//Create a yellow label to put in the content pane. JLabel yellowLabel = new JLabel();JLabel yellowLabel = new JLabel(); yellowLabel.setOpaque(true);yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131));yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180));yellowLabel.setPreferredSize(new Dimension(200, 180));
//Set the menu bar and add the label to the content pane.//Set the menu bar and add the label to the content pane. frame.setJMenuBar(greenMenuBar);frame.setJMenuBar(greenMenuBar); frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);frame.getContentPane().add(yellowLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1616
FramesFrames
Window with border, title and buttonsWindow with border, title and buttons
Making framesMaking frames• JFrame frame = new JFrame();JFrame frame = new JFrame();
Or extend JFrame class (often better code this way).Or extend JFrame class (often better code this way).
Style defined withStyle defined with
UIManager.setLookAndFeel(looknfeel);UIManager.setLookAndFeel(looknfeel);SwingUtilities.updateComponentTreeUI(frame);SwingUtilities.updateComponentTreeUI(frame);frame.pack();frame.pack();
1717
a JFrame examplea JFrame example//this won’t compile…//this won’t compile…public static void main(String[] args) public static void main(String[] args) {{
JFrame frame = new JFrame(“A JFrame"); //Just like any JFrame frame = new JFrame(“A JFrame"); //Just like any //other class //other class// do things with frame// do things with frameframe.setJMenuBar(menuBar);frame.setJMenuBar(menuBar);frame.setContentPane(contentPane);frame.setContentPane(contentPane);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// set frame size// set frame sizeframe.pack();frame.pack();
// realize frame// realize frameframe.setVisible(true);frame.setVisible(true);
} // end main} // end main
1818
a JFrame examplea JFrame example
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* FrameDemo.java requires no other files. *//* FrameDemo.java requires no other files. */public class FrameDemo {public class FrameDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() {
//Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("FrameDemo");JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100));emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
1919
a JFrame examplea JFrame example
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* FrameDemo.java requires no other files. *//* FrameDemo.java requires no other files. */public class FrameDemo {public class FrameDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("FrameDemo");JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100));emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
Adding Components to the Content Pane.
2020
a JFrame examplea JFrame example
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* FrameDemo.java requires no other files. *//* FrameDemo.java requires no other files. */public class FrameDemo {public class FrameDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("FrameDemo");JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100));emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) { //Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
2121
a JFrame examplea JFrame example
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;import javax.swing.*;import javax.swing.*;
/* FrameDemo.java requires no other files. *//* FrameDemo.java requires no other files. */public class FrameDemo {public class FrameDemo { /**/** * Create the GUI and show it. For thread safety,* Create the GUI and show it. For thread safety, * this method should be invoked from the* this method should be invoked from the * event-dispatching thread.* event-dispatching thread. */*/ private static void createAndShowGUI() {private static void createAndShowGUI() { //Create and set up the window.//Create and set up the window. JFrame frame = new JFrame("FrameDemo");JFrame frame = new JFrame("FrameDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");JLabel emptyLabel = new JLabel(""); emptyLabel.setPreferredSize(new Dimension(175, 100));emptyLabel.setPreferredSize(new Dimension(175, 100)); frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.//Display the window. frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}
public static void main(String[] args) {public static void main(String[] args) {
//Schedule a job for the event-dispatching thread://Schedule a job for the event-dispatching thread: //creating and showing this application's GUI.//creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() {javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() {public void run() { createAndShowGUI();createAndShowGUI(); }} });}); }}}}
2222
Examples 1 + 2Examples 1 + 2
SwingApplication.javaSwingApplication.java• Messy way.Messy way.
BetterSwingApp.javaBetterSwingApp.java• Neater way.Neater way.
2323
Examples 1Examples 1//--- SwingApplication.java//--- SwingApplication.java//---//---//--- This is a poor example of how to make a window appear. //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well.//--- It clearly illustrates what is happening, but does not scale well.//--- The next example improves upon the design.//--- The next example improves upon the design.
import javax.swing.*; import javax.swing.*; import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class SwingApplication {public class SwingApplication {
public Component createComponents() {public Component createComponents() {final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW");final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW");/*/** An easy way to put space between a top-level container* An easy way to put space between a top-level container* and its contents is to put the contents in a JPanel* and its contents is to put the contents in a JPanel* that has an "empty" border.* that has an "empty" border.*/*/JPanel pane = new JPanel();JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(pane.setBorder(BorderFactory.createEmptyBorder(30, //top30, //top30, //left30, //left10, //bottom10, //bottom30) //right30) //right););pane.add(label);pane.add(label);
return pane;return pane;}}
public static void main(String[] args) {public static void main(String[] args) {try {try {UIManager.setLookAndFeel(UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());UIManager.getCrossPlatformLookAndFeelClassName());} catch (Exception e) } catch (Exception e) { }{ }
//Create the top-level container and //Create the top-level container and JFrame frame = new JFrame("SwingApplication");JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class//Create an instance of the SwingApplication ClassSwingApplication app = new SwingApplication();SwingApplication app = new SwingApplication();
//Create the components//Create the componentsComponent contents = app.createComponents();Component contents = app.createComponents();
//Create new Jpanel for content pane//Create new Jpanel for content paneJPanel contentPane = new JPanel();JPanel contentPane = new JPanel();
//add them to the content pane of the main frame //add them to the content pane of the main frame contentPane.add(contents);contentPane.add(contents);
//Make new panel the content pane//Make new panel the content pane////contentPane.setOpaque(true);contentPane.setOpaque(true);frame.setContentPane(contentPane);frame.setContentPane(contentPane);
//enable the frame to close.//enable the frame to close.//NOTE - This is the old way, but included as an example of//NOTE - This is the old way, but included as an example of// - code you may see on the web// - code you may see on the webframe.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {System.exit(0);System.exit(0);}}});});
//layout and then show//layout and then showframe.pack();frame.pack();frame.setVisible(true); //replaces frame.show() / frame.hide()frame.setVisible(true); //replaces frame.show() / frame.hide()}}
}}
2424
Examples 1Examples 1//--- SwingApplication.java//--- SwingApplication.java//---//---//--- This is a poor example of how to make a window appear. //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well.//--- It clearly illustrates what is happening, but does not scale well.//--- The next example improves upon the design.//--- The next example improves upon the design.
import javax.swing.*; import javax.swing.*; import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class SwingApplication {public class SwingApplication {
public Component createComponents() {public Component createComponents() {final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW");final JLabel label = new JLabel("THIS IS A LABEL IN A WINDOW");
/*/** An easy way to put space between a top-level container* An easy way to put space between a top-level container* and its contents is to put the contents in a JPanel* and its contents is to put the contents in a JPanel* that has an "empty" border.* that has an "empty" border.*/*/JPanel pane = new JPanel();JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(pane.setBorder(BorderFactory.createEmptyBorder(30, //top30, //top30, //left30, //left10, //bottom10, //bottom30) //right30) //right););
pane.add(label);pane.add(label);
return pane;return pane;}}
public static void main(String[] args) {public static void main(String[] args) {try {try {
UIManager.setLookAndFeel(UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) } catch (Exception e) { }{ }
//Create the top-level container and //Create the top-level container and JFrame frame = new JFrame("SwingApplication");JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class//Create an instance of the SwingApplication ClassSwingApplication app = new SwingApplication();SwingApplication app = new SwingApplication();
//Create the components//Create the componentsComponent contents = app.createComponents();Component contents = app.createComponents();
//Create new Jpanel for content pane//Create new Jpanel for content paneJPanel contentPane = new JPanel();JPanel contentPane = new JPanel();
//add them to the content pane of the main frame //add them to the content pane of the main frame contentPane.add(contents);contentPane.add(contents);
//Make new panel the content pane//Make new panel the content pane////contentPane.setOpaque(true);contentPane.setOpaque(true);frame.setContentPane(contentPane);frame.setContentPane(contentPane);
//enable the frame to close.//enable the frame to close.//NOTE - This is the old way, but included as an example of//NOTE - This is the old way, but included as an example of// - code you may see on the web// - code you may see on the webframe.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {System.exit(0);System.exit(0);}}
});});
//layout and then show//layout and then showframe.pack();frame.pack();frame.setVisible(true); //replaces frame.show() / frame.hide()frame.setVisible(true); //replaces frame.show() / frame.hide()
}}}}
2525
Examples 1Examples 1//--- SwingApplication.java//--- SwingApplication.java//---//---//--- This is a poor example of how to make a window appear. //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well.//--- It clearly illustrates what is happening, but does not scale well.//--- The next example improves upon the design.//--- The next example improves upon the design.
import javax.swing.*; import javax.swing.*; import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public static void main(String[] args) {public static void main(String[] args) {try {try {UIManager.setLookAndFeel(UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName());UIManager.getCrossPlatformLookAndFeelClassName());} catch (Exception e) } catch (Exception e) { }{ }
//Create the top-level container and //Create the top-level container and JFrame frame = new JFrame("SwingApplication");JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class//Create an instance of the SwingApplication ClassSwingApplication app = new SwingApplication();SwingApplication app = new SwingApplication();//Create the components//Create the componentsComponent contents = app.createComponents();Component contents = app.createComponents();
//Create new Jpanel for content pane//Create new Jpanel for content paneJPanel contentPane = new JPanel();JPanel contentPane = new JPanel();
//add them to the content pane of the main frame //add them to the content pane of the main frame contentPane.add(contents);contentPane.add(contents);
//Make new panel the content pane//Make new panel the content pane////contentPane.setOpaque(true);contentPane.setOpaque(true);frame.setContentPane(contentPane);frame.setContentPane(contentPane);
//enable the frame to close.//enable the frame to close.//NOTE - This is the old way, but included as an example of//NOTE - This is the old way, but included as an example of// - code you may see on the web// - code you may see on the webframe.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {System.exit(0);System.exit(0);
}}});});
//layout and then show//layout and then showframe.pack();frame.pack();frame.setVisible(true); //replaces frame.show() / frame.hide()frame.setVisible(true); //replaces frame.show() / frame.hide()
}}}}
2626
Examples 1Examples 1//--- SwingApplication.java//--- SwingApplication.java//---//---//--- This is a poor example of how to make a window appear. //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well.//--- It clearly illustrates what is happening, but does not scale well.//--- The next example improves upon the design.//--- The next example improves upon the design.
import javax.swing.*; import javax.swing.*; import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public static void main(String[] args) {public static void main(String[] args) {try {try {UIManager.setLookAndFeel(UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName());UIManager.getCrossPlatformLookAndFeelClassName());} catch (Exception e) } catch (Exception e) { }{ }
//Create the top-level container and //Create the top-level container and JFrame frame = new JFrame("SwingApplication");JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class//Create an instance of the SwingApplication ClassSwingApplication app = new SwingApplication();SwingApplication app = new SwingApplication();
//Create the components//Create the componentsComponent contents = app.createComponents();Component contents = app.createComponents();
//Create new Jpanel for content pane//Create new Jpanel for content paneJPanel contentPane = new JPanel();JPanel contentPane = new JPanel();
//add them to the content pane of the main frame //add them to the content pane of the main frame contentPane.add(contents);contentPane.add(contents);
//Make new panel the content pane//Make new panel the content pane////contentPane.setOpaque(true);contentPane.setOpaque(true);frame.setContentPane(contentPane);frame.setContentPane(contentPane);
//enable the frame to close.//enable the frame to close.//NOTE - This is the old way, but included as an example of//NOTE - This is the old way, but included as an example of// - code you may see on the web// - code you may see on the webframe.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {System.exit(0);System.exit(0);
}}});});
//layout and then show//layout and then showframe.pack();frame.pack();frame.setVisible(true); //replaces frame.show() / frame.hide()frame.setVisible(true); //replaces frame.show() / frame.hide()
}}}}
2727
Examples 1Examples 1//--- SwingApplication.java//--- SwingApplication.java//---//---//--- This is a poor example of how to make a window appear. //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well.//--- It clearly illustrates what is happening, but does not scale well.//--- The next example improves upon the design.//--- The next example improves upon the design.
import javax.swing.*; import javax.swing.*; import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public static void main(String[] args) {public static void main(String[] args) {try {try {UIManager.setLookAndFeel(UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName());UIManager.getCrossPlatformLookAndFeelClassName());} catch (Exception e) } catch (Exception e) { }{ }
//Create the top-level container and //Create the top-level container and JFrame frame = new JFrame("SwingApplication");JFrame frame = new JFrame("SwingApplication");
//Create an instance of the SwingApplication Class//Create an instance of the SwingApplication ClassSwingApplication app = new SwingApplication();SwingApplication app = new SwingApplication();
//Create the components//Create the componentsComponent contents = app.createComponents();Component contents = app.createComponents();
//Create new Jpanel for content pane//Create new Jpanel for content paneJPanel contentPane = new JPanel();JPanel contentPane = new JPanel();
//add them to the content pane of the main frame //add them to the content pane of the main frame contentPane.add(contents);contentPane.add(contents);//Make new panel the content pane//Make new panel the content pane////contentPane.setOpaque(true);contentPane.setOpaque(true);frame.setContentPane(contentPane);frame.setContentPane(contentPane);
//enable the frame to close.//enable the frame to close.//NOTE - This is the old way, but included as an example of//NOTE - This is the old way, but included as an example of// - code you may see on the web// - code you may see on the webframe.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {System.exit(0);System.exit(0);
}}});});
//layout and then show//layout and then showframe.pack();frame.pack();frame.setVisible(true); //replaces frame.show() / frame.hide()frame.setVisible(true); //replaces frame.show() / frame.hide()
}}}}
2828
Examples 1Examples 1//--- SwingApplication.java//--- SwingApplication.java//---//---//--- This is a poor example of how to make a window appear. //--- This is a poor example of how to make a window appear. //--- It clearly illustrates what is happening, but does not scale well.//--- It clearly illustrates what is happening, but does not scale well.//--- The next example improves upon the design.//--- The next example improves upon the design.
import javax.swing.*; import javax.swing.*; import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public static void main(String[] args) {public static void main(String[] args) {try {try {
//Make new panel the content pane//Make new panel the content pane////contentPane.setOpaque(true);contentPane.setOpaque(true);frame.setContentPane(contentPane);frame.setContentPane(contentPane);
//enable the frame to close.//enable the frame to close.//NOTE - This is the old way, but included as an example of//NOTE - This is the old way, but included as an example of// - code you may see on the web// - code you may see on the webframe.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) {System.exit(0);System.exit(0);}}
});});
//layout and then show//layout and then showframe.pack();frame.pack();frame.setVisible(true); //replaces frame.show() / frame.hide()frame.setVisible(true); //replaces frame.show() / frame.hide()
}}}}
2929
Examples 2Examples 2// Example Java program to show some Swing ideas in practice// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)// First, import our swing packages (and the AWT stuff we usually need)import javax.swing.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.event.*;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class SwingExample extends JFrame public class SwingExample extends JFrame implements ActionListenerimplements ActionListener
{{// declare variables// declare variablesstatic JPanel contentPane;static JPanel contentPane;static JMenuBar menuBar;static JMenuBar menuBar;static JMenu fileMenu;static JMenu fileMenu;JMenuItem menuItem;JMenuItem menuItem;JButton helloButton;JButton helloButton;JButton goodbyeButton; JButton goodbyeButton; JLabel label;JLabel label;BorderLayout borderLayout;BorderLayout borderLayout;public SwingExample(String title)public SwingExample(String title){{
//Set title - passed in the constructor//Set title - passed in the constructorsetTitle(title); setTitle(title);
//enable to close - The new way//enable to close - The new waysetDefaultCloseOperation(EXIT_ON_CLOSE);setDefaultCloseOperation(EXIT_ON_CLOSE);
// set up menu bar// set up menu barmenuBar = new JMenuBar();menuBar = new JMenuBar();menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS));menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS));fileMenu = new JMenu("File");fileMenu = new JMenu("File");menuBar.add(fileMenu);menuBar.add(fileMenu);menuItem = new JMenuItem("Exit");menuItem = new JMenuItem("Exit");menuItem.setActionCommand("Exit");menuItem.setActionCommand("Exit");menuItem.addActionListener(this);menuItem.addActionListener(this);fileMenu.add(menuItem);fileMenu.add(menuItem);setJMenuBar(menuBar);setJMenuBar(menuBar);
// set up label// set up labellabel = new JLabel("Hello");label = new JLabel("Hello");label.setHorizontalAlignment(JLabel.CENTER);label.setHorizontalAlignment(JLabel.CENTER);
// set up buttons// set up buttonshelloButton = new JButton("Hello");helloButton = new JButton("Hello");helloButton.setActionCommand("Hi");helloButton.setActionCommand("Hi");helloButton.addActionListener(this);helloButton.addActionListener(this);
goodbyeButton = new JButton("Goodbye");goodbyeButton = new JButton("Goodbye");goodbyeButton.setActionCommand("Bye");goodbyeButton.setActionCommand("Bye");goodbyeButton.addActionListener(this);goodbyeButton.addActionListener(this);
//set up layout - not worry about now//set up layout - not worry about nowborderLayout = new BorderLayout();borderLayout = new BorderLayout();borderLayout.setHgap(5);borderLayout.setHgap(5);borderLayout.setVgap(10);borderLayout.setVgap(10);
// set layout of content pane// set layout of content panegetContentPane().setLayout(borderLayout);getContentPane().setLayout(borderLayout);
//add the contents//add the contentsgetContentPane().add(label, BorderLayout.NORTH);getContentPane().add(label, BorderLayout.NORTH);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(goodbyeButton, BorderLayout.WEST);getContentPane().add(goodbyeButton, BorderLayout.WEST);
//--- Now in 1.5 we can just use add() directly//--- Now in 1.5 we can just use add() directly//--- //--- //add(label, BorderLayout.NORTH);//add(label, BorderLayout.NORTH);//add(helloButton, BorderLayout.EAST);//add(helloButton, BorderLayout.EAST);//add(goodbyeButton, BorderLayout.WEST);//add(goodbyeButton, BorderLayout.WEST);
} // end constructor} // end constructor
//Message handlers - don't worry too much at this stage.//Message handlers - don't worry too much at this stage.public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){{
if ((e.getActionCommand()).equals("Exit"))if ((e.getActionCommand()).equals("Exit")){{
System.exit(0);System.exit(0);}}else if ((e.getActionCommand()).equals("Hi"))else if ((e.getActionCommand()).equals("Hi")){{
label.setText("Hello");label.setText("Hello");}}else if ((e.getActionCommand()).equals("Bye"))else if ((e.getActionCommand()).equals("Bye")){{
label.setText("Goodbye");label.setText("Goodbye");}}
} // end actionPerformed} // end actionPerformed
//Where it all begins - the main method//Where it all begins - the main methodpublic static void main(String[] args)public static void main(String[] args){{
//create instance of this class//create instance of this classSwingExample example = new SwingExample("Swing Example");SwingExample example = new SwingExample("Swing Example");
//layout and display the JFrame & its contents//layout and display the JFrame & its contentsexample.pack();example.pack();example.setVisible(true);example.setVisible(true);
} // end main} // end main} // end class Swing example} // end class Swing example
3030
Examples 2Examples 2// Example Java program to show some Swing ideas in practice// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)// First, import our swing packages (and the AWT stuff we usually need)import javax.swing.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.event.*;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class SwingExample extends JFrame public class SwingExample extends JFrame implements ActionListenerimplements ActionListener
{{
public SwingExample(String title)public SwingExample(String title){{
//Set title - passed in the constructor//Set title - passed in the constructorsetTitle(title); setTitle(title);
//enable to close - The new way//enable to close - The new waysetDefaultCloseOperation(EXIT_ON_CLOSE);setDefaultCloseOperation(EXIT_ON_CLOSE);
// set up menu bar// set up menu barmenuBar = new JMenuBar();menuBar = new JMenuBar();menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS));menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS));fileMenu = new JMenu("File");fileMenu = new JMenu("File");menuBar.add(fileMenu);menuBar.add(fileMenu);menuItem = new JMenuItem("Exit");menuItem = new JMenuItem("Exit");menuItem.setActionCommand("Exit");menuItem.setActionCommand("Exit");menuItem.addActionListener(this);menuItem.addActionListener(this);fileMenu.add(menuItem);fileMenu.add(menuItem);setJMenuBar(menuBar);setJMenuBar(menuBar);// set up label// set up labellabel = new JLabel("Hello");label = new JLabel("Hello");label.setHorizontalAlignment(JLabel.CENTER);label.setHorizontalAlignment(JLabel.CENTER);
// set up buttons// set up buttonshelloButton = new JButton("Hello");helloButton = new JButton("Hello");helloButton.setActionCommand("Hi");helloButton.setActionCommand("Hi");helloButton.addActionListener(this);helloButton.addActionListener(this);
goodbyeButton = new JButton("Goodbye");goodbyeButton = new JButton("Goodbye");goodbyeButton.setActionCommand("Bye");goodbyeButton.setActionCommand("Bye");goodbyeButton.addActionListener(this);goodbyeButton.addActionListener(this);
//set up layout - not worry about now//set up layout - not worry about nowborderLayout = new BorderLayout();borderLayout = new BorderLayout();borderLayout.setHgap(5);borderLayout.setHgap(5);borderLayout.setVgap(10);borderLayout.setVgap(10);
// set layout of content pane// set layout of content panegetContentPane().setLayout(borderLayout);getContentPane().setLayout(borderLayout);
//add the contents//add the contentsgetContentPane().add(label, BorderLayout.NORTH);getContentPane().add(label, BorderLayout.NORTH);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(goodbyeButton, BorderLayout.WEST);getContentPane().add(goodbyeButton, BorderLayout.WEST);
//--- Now in 1.5 we can just use add() directly//--- Now in 1.5 we can just use add() directly//--- //--- //add(label, BorderLayout.NORTH);//add(label, BorderLayout.NORTH);//add(helloButton, BorderLayout.EAST);//add(helloButton, BorderLayout.EAST);//add(goodbyeButton, BorderLayout.WEST);//add(goodbyeButton, BorderLayout.WEST);
} // end constructor} // end constructor
//Message handlers - don't worry too much at this stage.//Message handlers - don't worry too much at this stage.public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){{
if ((e.getActionCommand()).equals("Exit"))if ((e.getActionCommand()).equals("Exit")){{
System.exit(0);System.exit(0);}}else if ((e.getActionCommand()).equals("Hi"))else if ((e.getActionCommand()).equals("Hi")){{
label.setText("Hello");label.setText("Hello");}}else if ((e.getActionCommand()).equals("Bye"))else if ((e.getActionCommand()).equals("Bye")){{
label.setText("Goodbye");label.setText("Goodbye");}}
} // end actionPerformed} // end actionPerformed
//Where it all begins - the main method//Where it all begins - the main methodpublic static void main(String[] args)public static void main(String[] args){{
//create instance of this class//create instance of this classSwingExample example = new SwingExample("Swing Example");SwingExample example = new SwingExample("Swing Example");
//layout and display the JFrame & its contents//layout and display the JFrame & its contentsexample.pack();example.pack();example.setVisible(true);example.setVisible(true);
} // end main} // end main} // end class Swing example} // end class Swing example
3131
Examples 2Examples 2
// Example Java program to show some Swing ideas in practice// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)// First, import our swing packages (and the AWT stuff we usually need)import javax.swing.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.event.*;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class SwingExample extends JFrame public class SwingExample extends JFrame implements ActionListenerimplements ActionListener
{{
// set up label// set up labellabel = new JLabel("Hello");label = new JLabel("Hello");label.setHorizontalAlignment(JLabel.CENTER);label.setHorizontalAlignment(JLabel.CENTER);
// set up buttons// set up buttonshelloButton = new JButton("Hello");helloButton = new JButton("Hello");helloButton.setActionCommand("Hi");helloButton.setActionCommand("Hi");helloButton.addActionListener(this);helloButton.addActionListener(this);
goodbyeButton = new JButton("Goodbye");goodbyeButton = new JButton("Goodbye");goodbyeButton.setActionCommand("Bye");goodbyeButton.setActionCommand("Bye");goodbyeButton.addActionListener(this);goodbyeButton.addActionListener(this);
//set up layout - not worry about now//set up layout - not worry about nowborderLayout = new BorderLayout();borderLayout = new BorderLayout();borderLayout.setHgap(5);borderLayout.setHgap(5);borderLayout.setVgap(10);borderLayout.setVgap(10);
// set layout of content pane// set layout of content panegetContentPane().setLayout(borderLayout);getContentPane().setLayout(borderLayout);//add the contents//add the contentsgetContentPane().add(label, BorderLayout.NORTH);getContentPane().add(label, BorderLayout.NORTH);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(goodbyeButton, BorderLayout.WEST);getContentPane().add(goodbyeButton, BorderLayout.WEST);
//--- Now in 1.5 we can just use add() directly//--- Now in 1.5 we can just use add() directly//--- //--- //add(label, BorderLayout.NORTH);//add(label, BorderLayout.NORTH);//add(helloButton, BorderLayout.EAST);//add(helloButton, BorderLayout.EAST);//add(goodbyeButton, BorderLayout.WEST);//add(goodbyeButton, BorderLayout.WEST);
} // end constructor} // end constructor
//Message handlers - don't worry too much at this stage.//Message handlers - don't worry too much at this stage.public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){{
if ((e.getActionCommand()).equals("Exit"))if ((e.getActionCommand()).equals("Exit")){{
System.exit(0);System.exit(0);}}else if ((e.getActionCommand()).equals("Hi"))else if ((e.getActionCommand()).equals("Hi")){{
label.setText("Hello");label.setText("Hello");}}else if ((e.getActionCommand()).equals("Bye"))else if ((e.getActionCommand()).equals("Bye")){{
label.setText("Goodbye");label.setText("Goodbye");}}
} // end actionPerformed} // end actionPerformed
//Where it all begins - the main method//Where it all begins - the main methodpublic static void main(String[] args)public static void main(String[] args){{
//create instance of this class//create instance of this classSwingExample example = new SwingExample("Swing Example");SwingExample example = new SwingExample("Swing Example");
//layout and display the JFrame & its contents//layout and display the JFrame & its contentsexample.pack();example.pack();example.setVisible(true);example.setVisible(true);
} // end main} // end main} // end class Swing example} // end class Swing example
3232
Examples 2Examples 2// Example Java program to show some Swing ideas in practice// Example Java program to show some Swing ideas in practice
// First, import our swing packages (and the AWT stuff we usually need)// First, import our swing packages (and the AWT stuff we usually need)import javax.swing.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.event.*;import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class SwingExample extends JFrame public class SwingExample extends JFrame implements ActionListenerimplements ActionListener
{{
//add the contents//add the contentsgetContentPane().add(label, BorderLayout.NORTH);getContentPane().add(label, BorderLayout.NORTH);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(helloButton, BorderLayout.EAST);getContentPane().add(goodbyeButton, BorderLayout.WEST);getContentPane().add(goodbyeButton, BorderLayout.WEST);
//--- Now in 1.5 we can just use add() directly//--- Now in 1.5 we can just use add() directly//--- //--- //add(label, BorderLayout.NORTH);//add(label, BorderLayout.NORTH);//add(helloButton, BorderLayout.EAST);//add(helloButton, BorderLayout.EAST);//add(goodbyeButton, BorderLayout.WEST);//add(goodbyeButton, BorderLayout.WEST);} // end constructor} // end constructor
//Message handlers - don't worry too much at this stage.//Message handlers - don't worry too much at this stage.public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){{if ((e.getActionCommand()).equals("Exit"))if ((e.getActionCommand()).equals("Exit")){{System.exit(0);System.exit(0);}}else if ((e.getActionCommand()).equals("Hi"))else if ((e.getActionCommand()).equals("Hi")){{label.setText("Hello");label.setText("Hello");}}else if ((e.getActionCommand()).equals("Bye"))else if ((e.getActionCommand()).equals("Bye")){{label.setText("Goodbye");label.setText("Goodbye");}}} // end actionPerformed} // end actionPerformed
//Where it all begins - the main method//Where it all begins - the main methodpublic static void main(String[] args)public static void main(String[] args){{//create instance of this class//create instance of this classSwingExample example = new SwingExample("Swing Example");SwingExample example = new SwingExample("Swing Example");
//layout and display the JFrame & its contents//layout and display the JFrame & its contentsexample.pack();example.pack();example.setVisible(true);example.setVisible(true);} // end main} // end main
} // end class Swing example} // end class Swing example
3333
Examples 2Examples 2//Message handlers - don't worry too much at this stage.//Message handlers - don't worry too much at this stage.public void actionPerformed(ActionEvent e)public void actionPerformed(ActionEvent e){{
if ((e.getActionCommand()).equals("Exit"))if ((e.getActionCommand()).equals("Exit")){{
System.exit(0);System.exit(0);}}else if ((e.getActionCommand()).equals("Hi"))else if ((e.getActionCommand()).equals("Hi")){{
label.setText("Hello");label.setText("Hello");}}else if ((e.getActionCommand()).equals("Bye"))else if ((e.getActionCommand()).equals("Bye")){{
label.setText("Goodbye");label.setText("Goodbye");}}
} // end actionPerformed} // end actionPerformed
//Where it all begins - the main method//Where it all begins - the main methodpublic static void main(String[] args)public static void main(String[] args){{
//create instance of this class//create instance of this classSwingExample example = new SwingExample("Swing Example");SwingExample example = new SwingExample("Swing Example");
//layout and display the JFrame & its contents//layout and display the JFrame & its contentsexample.pack();example.pack();example.setVisible(true);example.setVisible(true);
} // end main} // end main} // end class Swing example} // end class Swing example
3434
Examples 2Examples 2//Where it all begins - the main method//Where it all begins - the main methodpublic static void main(String[] args)public static void main(String[] args){{
//create instance of this class//create instance of this classSwingExample example = new SwingExample example = new
SwingExample("Swing Example");SwingExample("Swing Example");
//layout and display the JFrame & its //layout and display the JFrame & its contentscontents
example.pack();example.pack();example.setVisible(true);example.setVisible(true);
} // end main} // end main} // end class Swing example} // end class Swing example
3535
Dialog boxesDialog boxes
More limited than framesMore limited than frames ModalityModality Types of dialogsTypes of dialogs
• JOptionPaneJOptionPane• ProgressMonitorProgressMonitor• JColorChooserJColorChooser• JDialogJDialog
3636
Showing dialogsShowing dialogs
JOptionPane.showXYZDialog(…)JOptionPane.showXYZDialog(…)• Option and Message dialogsOption and Message dialogs
JOptionPane.showMessageDialog(frame, ”Error!”, ”An error JOptionPane.showMessageDialog(frame, ”Error!”, ”An error message”, JOptionPane.ERROR_MESSAGE);message”, JOptionPane.ERROR_MESSAGE);
JOptionPane.showOptionDialog(frame, “Save?”, “A save JOptionPane.showOptionDialog(frame, “Save?”, “A save dialog”, JOptionPane.YES_NO_CANCEL_OPTION);dialog”, JOptionPane.YES_NO_CANCEL_OPTION);
• Input, ConfirmInput, Confirm
Customisation Customisation • showOptionDialog - Fairly customisableshowOptionDialog - Fairly customisable• JDialog - Totally customisableJDialog - Totally customisable
3737
Showing dialogsShowing dialogs
JOptionPane.showMessageDialog(frame, "Eggs are JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green."); not supposed to be green.");
3838
Example 3Example 3
DialogDemo.javaDialogDemo.java• Not looking at code in detail…Not looking at code in detail…
3939
Example 3Example 3//default icon, custom title //default icon, custom title int n = JOptionPane.showConfirmDialog( frame, "Would you like green eggs int n = JOptionPane.showConfirmDialog( frame, "Would you like green eggs and ham?", "An Inane Question", JOptionPane.YES_NO_OPTION); and ham?", "An Inane Question", JOptionPane.YES_NO_OPTION);
Object[] options = {"Yes, please", "No way!"}; int n = Object[] options = {"Yes, please", "No way!"}; int n = JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?", JOptionPane.showOptionDialog(frame, "Would you like green eggs and ham?", "A Silly Question", JOptionPane.YES_NO_OPTION, "A Silly Question", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, //do not use a custom Icon options, JOptionPane.QUESTION_MESSAGE, null, //do not use a custom Icon options, //the titles of buttons options[0]); //default button title //the titles of buttons options[0]); //default button title
4040
AppletsApplets
Not covered in great detail hereNot covered in great detail here
JApplet is a top-level containerJApplet is a top-level container• has menu bar and content pane supporthas menu bar and content pane support
JApplet supports assistive technologiesJApplet supports assistive technologies
Requires Java plug-in for browserRequires Java plug-in for browser• consider user groupconsider user group
4141
Intermediate containers – Intermediate containers – Panels (or ‘panes’)Panels (or ‘panes’)
Root panesRoot panes• The content paneThe content pane• Layered panesLayered panes• Glass panesGlass panes
• optional menu baroptional menu bar
4242
Intermediate containers – Intermediate containers – Panels (or ‘panes’)Panels (or ‘panes’)
Root panesRoot panes• The content paneThe content pane• Layered panesLayered panes• Glass panesGlass panes
• optional menu baroptional menu bar
You get a JRootPane (whether you want it or not!)
when you instantiate JInternalFrame or one of the top-level Swing containers,
such as JApplet, JDialog, and JFrame.
4343
Root panesRoot panes ‘‘Invisibly’ attached to top-level containerInvisibly’ attached to top-level container
Created by Swing on realizing frameCreated by Swing on realizing frame
Manages everything between top-level container Manages everything between top-level container and componentsand components
Places menu bar and content pane in an instance of Places menu bar and content pane in an instance of JLayeredPane (see a couple of slides on)JLayeredPane (see a couple of slides on)
4444
Content panesContent panes
Usually use a JPanelUsually use a JPanel Contains everything except menu bar for most Contains everything except menu bar for most
Swing applicationsSwing applications Can be explicitly, orCan be explicitly, or
implicitly created,implicitly created,• see (simplified) codesee (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);
4545
Example 4Example 4
TopLevelDemo.javaTopLevelDemo.java• Illustrates the Content Pane, and Illustrates the Content Pane, and
Menu Bar positioning (see slides 10 Menu Bar positioning (see slides 10 -15).-15).
4646
Layered panesLayered panes Provided by root pane, but can also be Provided by root pane, but can also be
createdcreated Provides depth (z-buffering) to Provides depth (z-buffering) to
componentscomponents ‘‘Depth’ is specified as integerDepth’ is specified as integer
• Frame content (-30000, content pane, menu bar)Frame content (-30000, content pane, menu bar)• Default (0, components)Default (0, components)• Palette (100, toolbars and palettes)Palette (100, toolbars and palettes)• Modal (200, internal dialogs)Modal (200, internal dialogs)• Popup (300, external dialogs)Popup (300, external dialogs)• Drag (400, component when dragged)Drag (400, component when dragged)
4747
Layered panesLayered panes Provided by root pane, but can also be Provided by root pane, but can also be
createdcreated Provides depth (z-buffering) to Provides depth (z-buffering) to
componentscomponents ‘‘Depth’ is specified as integerDepth’ is specified as integer
• Frame content (-30000, content pane, menu bar)Frame content (-30000, content pane, menu bar)• Default (0, components)Default (0, components)• Palette (100, toolbars and palettes)Palette (100, toolbars and palettes)• Modal (200, internal dialogs)Modal (200, internal dialogs)• Popup (300, external dialogs)Popup (300, external dialogs)• Drag (400, component when dragged)Drag (400, component when dragged)
overlapping components can appear one on top of the other How to use toot pane
4848
Example 5Example 5
LayeredPaneDemo.javaLayeredPaneDemo.java
4949
Example 5Example 5import javax.swing.*;import javax.swing.*;import javax.swing.border.*;import javax.swing.border.*;import javax.accessibility.*;import javax.accessibility.*;
import java.awt.*;import java.awt.*;import java.awt.event.*;import java.awt.event.*;
public class LayeredPaneDemo extends JFrame {public class LayeredPaneDemo extends JFrame { private String[] layerStrings = { "Yellow (0)", "Magenta (1)", private String[] layerStrings = { "Yellow (0)", "Magenta (1)", "Cyan (2)", "Red (3)", "Cyan (2)", "Red (3)", "Green (4)" };"Green (4)" }; private Color[] layerColors = { Color.yellow, Color.magenta, private Color[] layerColors = { Color.yellow, Color.magenta, Color.cyan, Color.red,Color.cyan, Color.red, Color.green };Color.green };
private JLayeredPane layeredPane;private JLayeredPane layeredPane; private JLabel dukeLabel;private JLabel dukeLabel;
public LayeredPaneDemo() {public LayeredPaneDemo() { super("LayeredPaneDemo");super("LayeredPaneDemo");
//Create and load the duke icon.//Create and load the duke icon. final ImageIcon icon = new ImageIcon("duke.gif");final ImageIcon icon = new ImageIcon("duke.gif");
//Create and set up the layered pane.//Create and set up the layered pane. layeredPane = new JLayeredPane();layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 310));layeredPane.setPreferredSize(new Dimension(300, 310)); layeredPane.setBorder(BorderFactory.createTitledBorder(layeredPane.setBorder(BorderFactory.createTitledBorder( "Move the Mouse to Move Duke"));"Move the Mouse to Move Duke")); layeredPane.addMouseMotionListener(new MouseMotionAdapter() {layeredPane.addMouseMotionListener(new MouseMotionAdapter() { final int XFUDGE = 40;final int XFUDGE = 40; final int YFUDGE = 57;final int YFUDGE = 57; public void mouseEntered(MouseEvent e) {public void mouseEntered(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); }} public void mouseMoved(MouseEvent e) {public void mouseMoved(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); }} });});
//This is the origin of the first label added.//This is the origin of the first label added. Point origin = new Point(10, 20);Point origin = new Point(10, 20);
//This is the offset for computing the origin for the next label.//This is the offset for computing the origin for the next label. int offset = 35;int offset = 35;
//Add several overlapping, colored labels to the layered pane//Add several overlapping, colored labels to the layered pane //using absolute positioning/sizing.//using absolute positioning/sizing. for (int i = 0; i < layerStrings.length; i++) {for (int i = 0; i < layerStrings.length; i++) { JLabel label = createColoredLabel(layerStrings[i],JLabel label = createColoredLabel(layerStrings[i], layerColors[i], origin);layerColors[i], origin); layeredPane.add(label, new Integer(i)); layeredPane.add(label, new Integer(i)); origin.x += offset;origin.x += offset; origin.y += offset;origin.y += offset; }}
//Create and add the Duke label to the layered pane.//Create and add the Duke label to the layered pane. dukeLabel = new JLabel(icon);dukeLabel = new JLabel(icon); dukeLabel.setBounds(15, 225, dukeLabel.setBounds(15, 225, icon.getIconWidth(),icon.getIconWidth(), icon.getIconHeight());icon.getIconHeight()); layeredPane.add(dukeLabel, new Integer(2), 0);layeredPane.add(dukeLabel, new Integer(2), 0);
//Add control pane and layered pane to frame.//Add control pane and layered pane to frame. Container contentPane = getContentPane();Container contentPane = getContentPane(); contentPane.setLayout(new BoxLayout(contentPane,contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));BoxLayout.Y_AXIS)); contentPane.add(Box.createRigidArea(new Dimension(0, 10)));contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(createControlPanel());contentPane.add(createControlPanel()); contentPane.add(Box.createRigidArea(new Dimension(0, 10)));contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(layeredPane);contentPane.add(layeredPane); }}
//Create and set up a colored label.//Create and set up a colored label. private JLabel createColoredLabel(String text, private JLabel createColoredLabel(String text, Color color,Color color, Point origin) {Point origin) { JLabel label = new JLabel(text);JLabel label = new JLabel(text); label.setVerticalAlignment(JLabel.TOP);label.setVerticalAlignment(JLabel.TOP); label.setHorizontalAlignment(JLabel.CENTER);label.setHorizontalAlignment(JLabel.CENTER); label.setOpaque(true);label.setOpaque(true); label.setBackground(color);label.setBackground(color); label.setForeground(Color.black);label.setForeground(Color.black); label.setBorder(BorderFactory.createLineBorder(Color.black));label.setBorder(BorderFactory.createLineBorder(Color.black)); label.setBounds(origin.x, origin.y, 140, 140);label.setBounds(origin.x, origin.y, 140, 140); return label;return label; }}
//Create the control pane for the top of the frame.//Create the control pane for the top of the frame. private JPanel createControlPanel() {private JPanel createControlPanel() { final JCheckBox onTop = new JCheckBox("Top Position in Layer");final JCheckBox onTop = new JCheckBox("Top Position in Layer"); onTop.setSelected(true);onTop.setSelected(true); onTop.addActionListener(new ActionListener() {onTop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { if (onTop.isSelected())if (onTop.isSelected()) layeredPane.moveToFront(dukeLabel);layeredPane.moveToFront(dukeLabel); elseelse layeredPane.moveToBack(dukeLabel);layeredPane.moveToBack(dukeLabel); }} });});
final JComboBox layerList = new JComboBox(layerStrings);final JComboBox layerList = new JComboBox(layerStrings); layerList.setSelectedIndex(2); //Cyan layerlayerList.setSelectedIndex(2); //Cyan layer layerList.addActionListener(new ActionListener () {layerList.addActionListener(new ActionListener () { public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { int position = onTop.isSelected() ? 0 : 1;int position = onTop.isSelected() ? 0 : 1; layeredPane.setLayer(dukeLabel,layeredPane.setLayer(dukeLabel, layerList.getSelectedIndex(),layerList.getSelectedIndex(), position);position); }} });}); JPanel controls = new JPanel();JPanel controls = new JPanel(); controls.add(layerList);controls.add(layerList); controls.add(onTop);controls.add(onTop); controls.setBorder(BorderFactory.createTitledBorder(controls.setBorder(BorderFactory.createTitledBorder( "Choose Duke's Layer and Position"));"Choose Duke's Layer and Position")); return controls;return controls; }}
public static void main(String[] args) {public static void main(String[] args) { JFrame frame = new LayeredPaneDemo();JFrame frame = new LayeredPaneDemo();
frame.addWindowListener(new WindowAdapter() {frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {public void windowClosing(WindowEvent e) { System.exit(0);System.exit(0); }} });});
frame.pack();frame.pack(); frame.setVisible(true);frame.setVisible(true); }}}}
5050
Example 5Example 5
//Create and set up the layered pane.//Create and set up the layered pane. layeredPane = new JLayeredPane();layeredPane = new JLayeredPane(); layeredPane.setPreferredSize(new Dimension(300, 310));layeredPane.setPreferredSize(new Dimension(300, 310)); layeredPane.setBorder(BorderFactory.createTitledBorder(layeredPane.setBorder(BorderFactory.createTitledBorder( "Move the Mouse to Move Duke"));"Move the Mouse to Move Duke")); layeredPane.addMouseMotionListener(new MouseMotionAdapter() layeredPane.addMouseMotionListener(new MouseMotionAdapter()
{{ final int XFUDGE = 40;final int XFUDGE = 40; final int YFUDGE = 57;final int YFUDGE = 57; public void mouseEntered(MouseEvent e) {public void mouseEntered(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); }} public void mouseMoved(MouseEvent e) {public void mouseMoved(MouseEvent e) { dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE);dukeLabel.setLocation(e.getX()-XFUDGE, e.getY()-YFUDGE); }} });});
5151
Example 5Example 5//Create and add the Duke label to the layered pane.//Create and add the Duke label to the layered pane. dukeLabel = new JLabel(icon);dukeLabel = new JLabel(icon); dukeLabel.setBounds(15, 225, dukeLabel.setBounds(15, 225, icon.getIconWidth(),icon.getIconWidth(), icon.getIconHeight());icon.getIconHeight()); layeredPane.add(dukeLabel, new Integer(2), 0);layeredPane.add(dukeLabel, new Integer(2), 0);
//Add control pane and layered pane to frame.//Add control pane and layered pane to frame. Container contentPane = getContentPane();Container contentPane = getContentPane(); contentPane.setLayout(new BoxLayout(contentPane,contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));BoxLayout.Y_AXIS)); contentPane.add(Box.createRigidArea(new Dimension(0, 10)));contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(createControlPanel());contentPane.add(createControlPanel()); contentPane.add(Box.createRigidArea(new Dimension(0, 10)));contentPane.add(Box.createRigidArea(new Dimension(0, 10))); contentPane.add(layeredPane);contentPane.add(layeredPane); }}
5252
Example 5Example 5//Create the control pane for the top of the frame.//Create the control pane for the top of the frame. private JPanel createControlPanel() {private JPanel createControlPanel() { final JCheckBox onTop = new JCheckBox("Top Position in final JCheckBox onTop = new JCheckBox("Top Position in
Layer");Layer"); onTop.setSelected(true);onTop.setSelected(true); onTop.addActionListener(new ActionListener() {onTop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {public void actionPerformed(ActionEvent e) { if (onTop.isSelected())if (onTop.isSelected()) layeredPane.moveToFront(dukeLabel);layeredPane.moveToFront(dukeLabel); elseelse layeredPane.moveToBack(dukeLabel);layeredPane.moveToBack(dukeLabel); }} });});
5353
Glass panesGlass panes
Not structured into componentsNot structured into components• event catchingevent catching• paintingpainting
Used for ‘weird’ interface behavior, Used for ‘weird’ interface behavior, rarely used.rarely used.
Either created explicitly or root Either created explicitly or root version usedversion used
5454
Example 6Example 6
GlassPaneDemo.javaGlassPaneDemo.java
5555
Example 6Example 6 It contains a check box that lets you set It contains a check box that lets you set
whether the glass pane is "visible" — whether the glass pane is "visible" — whether it can get events and paint itself whether it can get events and paint itself onscreen. onscreen.
When the glass pane is visible, it blocks all When the glass pane is visible, it blocks all input events from reaching the input events from reaching the components in the content pane. components in the content pane.
It also paints a red dot in the place where It also paints a red dot in the place where it last detected a mouse-pressed event. it last detected a mouse-pressed event.
5656
ComponentsComponents
Content of your interfaceContent of your interface• http://java.sun.com/docs/books/tutorial/uiswinghttp://java.sun.com/docs/books/tutorial/uiswing
/components/components.html/components/components.html
Created just like any class instanceCreated just like any class instance• JButton button_ok = new JButton(“OK”);JButton button_ok = new JButton(“OK”);
Range in complexity from very simple (e.g. Range in complexity from very simple (e.g. JButton) to very detailed (e.g. JButton) to very detailed (e.g. JColorChooser)JColorChooser)
5757
Swing and AWT components - Swing and AWT components - a quick remindera quick reminder
Mix Swing and AWT components as Mix Swing and AWT components as little as possible (not at all in most little as possible (not at all in most cases)cases)
Put ‘J’ in front of everything AWT Put ‘J’ in front of everything AWT provides to get Swing’s counterpartprovides to get Swing’s counterpart• AWT: ButtonAWT: Button• Swing: JButtonSwing: JButton
5858
Atomic componentsAtomic components
ButtonsButtons Combo boxesCombo boxes ListsLists MenusMenus SlidersSliders Text FieldsText Fields LabelsLabels
5959
Atomic components Atomic components
Tool tipsTool tips Progress barsProgress bars Colour choosersColour choosers File choosersFile choosers TablesTables TextText TreesTrees
6060
Atomic componentsAtomic components
Impossible to teach the working of every type of Impossible to teach the working of every type of componentcomponent
Very few people know it all! – Swing is HUGE.Very few people know it all! – Swing is HUGE. Remember to refer to:Remember to refer to:
• Swing tutorialSwing tutorial• The Java 2 API Documentation.The Java 2 API Documentation.• The Visual index to components & containers at The Visual index to components & containers at
java.sun.com: java.sun.com: http://java.sun.com/docs/books/tutorial/uiswing/components/compohttp://java.sun.com/docs/books/tutorial/uiswing/components/compo
nents.htmlnents.html
6161
SummarySummary Containers (Frames and Dialogs)Containers (Frames and Dialogs)
• HierarchyHierarchy• Root PanesRoot Panes• Layered PanesLayered Panes• Content PanesContent Panes• Glass PanesGlass Panes
ComponentsComponents• Lots of ‘em…Lots of ‘em…
Next timeNext time• Layout Management.Layout Management.