1 Java Swing - Components and Containment. 2 Components and Containers Components and Containers Components Components The building blocksThe building.

Slides:



Advertisements
Similar presentations
Components and Containers
Advertisements

Introduction to JFC Swing Written by Adam Carmi. Agenda About JFC and Swing Pluggable Look and Feel Swing Components Borders Layout Management Events.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Understanding SWING Architecture CS 4170 UI Design Hrvoje Benko Oct. 9, 2001.
Object-Oriented Software Engineering Java with added Swing.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
Graphical User Interfaces
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
CPSC150 JavaLynn Lambert CPSC150 Week 12 InheritanceInterfaces.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
Contructing GUI’s in Java Implemented in the Swing API Imported into your programs by: import javax.swing.*; Most Swing programs also need the AWT packages.
Java Swing Joon Ho Cho. What is Java Swing? Part of the Java Foundation Classes (JFC) Provides a rich set of GUI components Used to create a Java program.
CC1007NI: Further Programming Week 5 Dhruba Sen Module Leader (Islington College)
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
GUI Basics: Introduction. Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your.
Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.
Java Swing © Walter Milner 2005: Slide 1 Java Swing Walter Milner.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
Intro to GUIs (Graphical User Interfaces) Section 2.5Intro. to GUIs: a GUI Greeter Section 3.7Graphical/Internet Java: Einstein's Equation.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
CS377A: A Programming Approach to HCI Jan Borchers Spring Swing Refresher David Merrill 5/14/2002
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
Chapter 9: Visual Programming Basics Object-Oriented Program Development Using Java: A Class-Centered Approach.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
FEN IntroJava2006 AAU1 GUI: Graphical User Interface AWT/SWING: Components Drag and Drop in NetBeans Events Listeners.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
CompSci 100E 35.1 Graphical User Interfaces: GUIs  Components  Flat Layouts  Hierarchical Layouts  Designing a GUI  Coding a GUI.
Concurrent Programming and Threads Threads Blocking a User Interface.
1 Java Swing - Lecture 2 Components and Containment Boriana Koleva
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Announcements/Reminders l Next week: »No Lectures »No Labs »Recitation.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Programming with Java’s Swing API February 4, 2003 CMPS Advanced Programming Graphical User Interfaces.
Java Applet. Introductions Applet is java program that can be embedded into HTML pages Java applets runs on the java enables web browsers such as mozila.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Object-Oriented Software Engineering
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Creating and Using Dialogs ● A dialog is a box that pops up and prompts the user for a value or informs them of something ● One way: directly create objects.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 3: Layout Basics.
1 IM103 week 10 Enhancing the user interface By the end of lecture you should be able to:  distinguish between heavyweight and lightweight components;
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
Objects First With Java A Practical Introduction Using BlueJ Building Graphical User Interfaces (GUIs) Week
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
Chapter 6 Building Java GUIs. MVC Model View Controller The model passes its data to the view for rendering The view determines which events are passed.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Java Swing. Note - this presentation.. often needs to refer to source code which is too big to put on a slide So the source code is in a separate Word.
Module 13: Swing API Object Oriented Programming(Java)
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
University of Central Florida COP 3330 Object Oriented Programming
A Quick Java Swing Tutorial
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced Programming in Java
Graphical User Interface
Presentation transcript:

1 Java Swing - Components and Containment

2 Components and Containers Components and Containers Components Components The building blocksThe building blocks Variety of uses and complexitiesVariety of uses and complexities Containers Containers The cementThe cement Hierarchical organisationHierarchical organisation Distinction is not always drawnDistinction is not always drawn

3 Containment hierarchies Top level containers Top level containers Intermediate containersIntermediate containers Atomic components Atomic components Viewing containment hierarchies Viewing containment hierarchies

4 Top-level containers At the root of every containment hierarchy At the root of every containment hierarchy All Swing programs have at least one All Swing programs have at least one Content panes Content panes Types of top-level containers Types of top-level containers FramesFrames DialogsDialogs AppletsApplets

5 Using Top-Level Containers To appear onscreen, every GUI component must be part of a containment hierarchy. 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. 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. We'll show you one in a bit.

6 Using Top-Level Containers Each GUI component can be contained only once. 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. 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.

7 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. 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.

8 Using Top-Level Containers You can optionally add a menu bar to a top- level container. You can optionally add a menu bar to a top- level container. The menu bar is by convention positioned within the top-level container, but outside the content pane. 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. 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.

9 Using Top-Level Containers

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, * 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(); } }); }); }}

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, * 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(); } }); }); }}

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, * 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(); } }); }); }}

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, * 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(); } }); }); }}

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, * 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(); } }); }); }}

15 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, * 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(); } }); }); }}

16 Frames Window with border, title and buttons Window with border, title and buttons Making frames Making frames JFrame frame = new JFrame();JFrame frame = new JFrame(); Or extend JFrame class (often better code this way). Style defined with Style defined withUIManager.setLookAndFeel(looknfeel);SwingUtilities.updateComponentTreeUI(frame);frame.pack();

17 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

18 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, * 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(); } }); }); }}

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, * 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.

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, * 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(); } }); }); }}

21 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, * 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(); } }); }); }}

22 Examples SwingApplication.java SwingApplication.java Messy way.Messy way. BetterSwingApp.java BetterSwingApp.java Neater way.Neater way.

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 );pane.add(label); return pane; } 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. //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);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

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 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 );pane.add(label); return pane; } 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. //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);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

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 //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);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

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. //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);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

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 { 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. //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);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

28 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);}}); //layout and then show frame.pack(); frame.setVisible(true); //replaces frame.show() / frame.hide() }}

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 { // 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 menuBar = new JMenuBar(); menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.X_AXIS)); fileMenu = new JMenu("File"); menuBar.add(fileMenu); menuItem = new JMenuItem("Exit"); menuItem.setActionCommand("Exit");menuItem.addActionListener(this);fileMenu.add(menuItem);setJMenuBar(menuBar); // 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); 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")) {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"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

30 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"); menuItem.setActionCommand("Exit");menuItem.addActionListener(this);fileMenu.add(menuItem);setJMenuBar(menuBar); // 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); 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")) {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"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

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 { // 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); 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")) {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"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

32 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")) {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"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

33 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"); //layout and display the JFrame & its contents example.pack();example.setVisible(true); } // end main } // end class Swing example

34 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

35 Dialog boxes Dialog boxes More limited than frames More limited than frames Modality Modality Types of dialogs Types of dialogs JOptionPaneJOptionPane ProgressMonitorProgressMonitor JColorChooserJColorChooser JDialogJDialog

36 Showing dialogs JOptionPane.showXYZDialog(…) JOptionPane.showXYZDialog(…) Option and Message dialogsOption 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); JOptionPane.showOptionDialog(frame, “Save?”, “A save dialog”, JOptionPane.YES_NO_CANCEL_OPTION); Input, ConfirmInput, Confirm Customisation Customisation showOptionDialog - Fairly customisableshowOptionDialog - Fairly customisable JDialog - Totally customisableJDialog - Totally customisable

37 Showing dialogs JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");

38 Example 3 DialogDemo.java DialogDemo.java DialogDemo.java Not looking at code in detail…Not looking at code in detail…

39 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

40 Applets Not covered in great detail here Not covered in great detail here JApplet is a top-level container JApplet is a top-level container has menu bar and content pane supporthas menu bar and content pane support JApplet supports assistive technologies JApplet supports assistive technologies Requires Java plug-in for browser Requires Java plug-in for browser consider user groupconsider user group

41 Intermediate containers – Panels (or ‘panes’) Root panes Root panes Root panes Root panes The content paneThe content pane Layered panesLayered panes Glass panesGlass panes optional menu baroptional menu bar

42 Intermediate containers – Panels (or ‘panes’) Root panes Root panes Root panes Root 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. JInternalFrameJAppletJDialog JFrame

43 Root panes ‘Invisibly’ attached to top-level container ‘Invisibly’ attached to top-level container Created by Swing on realizing frame Created by Swing on realizing frame Manages everything between top-level container and components 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) Places menu bar and content pane in an instance of JLayeredPane (see a couple of slides on)

44 Content panes Usually use a JPanel Usually use a JPanel Contains everything except menu bar for most Swing applications Contains everything except menu bar for most Swing applications Can be explicitly, or Can be explicitly, or 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);

45 Example 4 TopLevelDemo.java TopLevelDemo.java Illustrates the Content Pane, and Menu Bar positioning (see slides ).Illustrates the Content Pane, and Menu Bar positioning (see slides ).

46 Layered panes Provided by root pane, but can also be created Provided by root pane, but can also be created Provides depth (z-buffering) to components Provides depth (z-buffering) to components ‘Depth’ is specified as integer ‘Depth’ 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)

47 Layered panes Provided by root pane, but can also be created Provided by root pane, but can also be created Provides depth (z-buffering) to components Provides depth (z-buffering) to components ‘Depth’ is specified as integer ‘Depth’ 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

48 Example 5 LayeredPaneDemo.java LayeredPaneDemo.java

49 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)", 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); else else layeredPane.moveToBack(dukeLabel); layeredPane.moveToBack(dukeLabel); } }); }); final JComboBox layerList = new JComboBox(layerStrings); final JComboBox layerList = new JComboBox(layerStrings); layerList.setSelectedIndex(2); //Cyan layer layerList.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); }}

50 Example 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); } }); });

51 Example 5 //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); }

52 Example 5 //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); else else layeredPane.moveToBack(dukeLabel); layeredPane.moveToBack(dukeLabel); } }); });

53 Glass panes Not structured into components Not structured into components event catchingevent catching paintingpainting Used for ‘weird’ interface behavior, rarely used. Used for ‘weird’ interface behavior, rarely used. Either created explicitly or root version used Either created explicitly or root version used

54 Example 6 GlassPaneDemo.java GlassPaneDemo.java

55 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. 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. 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. It also paints a red dot in the place where it last detected a mouse-pressed event.

56 Components Content of your interface Content of your interface ng/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswi ng/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswi ng/components/components.htmlhttp://java.sun.com/docs/books/tutorial/uiswi ng/components/components.html Created just like any class instance Created 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. JButton) to very detailed (e.g. JColorChooser) Range in complexity from very simple (e.g. JButton) to very detailed (e.g. JColorChooser)

57 Swing and AWT components - a quick reminder Mix Swing and AWT components as little as possible (not at all in most cases) 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 Put ‘J’ in front of everything AWT provides to get Swing’s counterpart AWT: ButtonAWT: Button Swing: JButtonSwing: JButton

58 Atomic components Buttons Buttons Combo boxes Combo boxes Lists Lists Menus Menus Sliders Sliders Text Fields Text Fields Labels Labels

59 Atomic components Tool tips Tool tips Progress bars Progress bars Colour choosers Colour choosers File choosers File choosers Tables Tables Text Text Trees Trees

60 Atomic components Impossible to teach the working of every type of component Impossible to teach the working of every type of component 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 java.sun.com:The Visual index to components & containers at java.sun.com: ponents.html ponents.html ponents.html ponents.html

61 Summary Containers (Frames and Dialogs) Containers (Frames and Dialogs) HierarchyHierarchy Root PanesRoot Panes Layered PanesLayered Panes Content PanesContent Panes Glass PanesGlass Panes Components Components Lots of ‘em…Lots of ‘em… Next time Next time Layout Management.Layout Management.