Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Corresponds with Chapter 12
Introduction to JFC Swing Written by Adam Carmi. Agenda About JFC and Swing Pluggable Look and Feel Swing Components Borders Layout Management Events.
Unit 091 Introduction to GUI Programming Introduction to User Interfaces Introduction to GUI Programming GUI Design Issues GUI Programming Issues Java.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Understanding SWING Architecture CS 4170 UI Design Hrvoje Benko Oct. 9, 2001.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
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.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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 Week 12 Graphical User Interfaces Chapter 11.
Creating GUIs in Java using Swing David Meredith Aalborg University.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Graphical User Interface (GUI) Design using Swing Course Lecture Slides.
GUI Basics: Introduction. Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your.
Java Programming Chapter 10 Graphical User Interfaces.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Learn about the types of Graphics that are available Develop a basic Graphics applet Develop a basic Graphics application Review the Java API and use.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
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.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
Lab 6: Shapes & Picture Extended Ellipse & Rectangle Classes Stand-Alone GUI Applications.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
10/24/20151 Java GUI Programming. 10/24/20152 What is a GUI? Java has standard packages for creating custom Graphical User Interfaces Some of the fundamental.
Chapter 9: Visual Programming Basics Object-Oriented Program Development Using Java: A Class-Centered Approach.
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.
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.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
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.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
Object Oriented programming Instructor: Dr. Essam H. Houssein.
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.
CSCI Swing1 The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness –The Abstract.
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.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
Creating Windows. How can we use Java to create programs that use windows (GUI applications)? How can we use Java to create programs that use windows.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Review_6 AWT, Swing, ActionListener, and Graphics.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Basics of GUI Programming Chapter 11 and Chapter 22.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
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: JFC and Swing Basics OOP tirgul No
Module 13: Swing API Object Oriented Programming(Java)
Chapter 9: Graphical User Interfaces
University of Central Florida COP 3330 Object Oriented Programming
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Steps to Creating a GUI Interface
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Introduction to Java GUI Creating Graphical User Interfaces © copyright Bobby Hoggard / material may not be redistributed without permission

Import Packages for GUI java.awt.* AWT (abstract window toolkit) is the main Java package used to create and display GUI objects AWT heavily relies on the native operating system to create and display the graphical objects As a result, your GUI interfaces will not look the same on every system “heavyweight” components

Import Packages for GUI javax.swing.* Swing is a package of GUI objects which is more-or-less pure Java Swing uses AWT to create a window, and then paints pictures of GUI objects inside the window, instead of relying on the operating system to do this As a result, your GUI interfaces should look about the same on every system Swing allows for a pluggable look and feel to easily change the style “lightweight” components (mostly)

Containers GUI objects are grouped together inside some type of container object To create a graphical user interface for a Java program, you must: Create a container object Add GUI components to the container object Add code which will execute in response to the object events This concept is no different from any other data structure that you would have previously used

Containers are Data Structures Linked Lists LinkedList list = new LinkedList(); list.add(data1); list.add(data2); Containers Container container = new Container(); container.add(obj1); container.add(obj2); data1 head list obj1obj2 head container

Top-Level Containers Top-level containers are the main containers for a Java program A Java GUI program begins by creating a top-level container, and then adds GUI components to it Top-level containers can appear on their own on the screen – all other types of containers must go inside a top-level container

Container Hierarchy All top-level containers classes are children of the Container class, which is derived from the Component class of the java.awt package The main window for a desktop application is a JFrame whereas the main container for a browser applet is JApplet Component Container Panel Applet JApplet Window JWindow JDialog JFrame

Types of Windows JFrame: Contains a title bar, menu bars, and a border. Can be minimized/maximized/closed. JDialog: Used to create dialog boxes. Often used to obtain more detailed user input or show more detailed output. JWindow: Has no trimmings. Often used for pop-up windows and splash screens.

Container Layers Root Pane: Manages/contains all of the layers. Layered Pane: Serves to position its contents in regards to depth (called Z order). Allows overlapping components to appear on top of each other. Holds content and menu. Menu Bar: The home for the root container’s menus Content Pane: Container for the root pane’s visible components (excluding the menu bar). Glass Pane: Acts like a sheet of glass over all other layers. It is completely transparent unless you paint something on it. Root Pane Layered Pane Content Pane Glass Pane Menu Bar

Hello World Example package example01; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } }

Make It Better package example01; import javax.swing.*; public class HelloWorld { public static void main(String[] args) { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true); } package example01; import javax.swing.*; public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); } public static void main(String[] args) { JFrame mainframe = createGUI(); mainframe.setVisible(true); }

Threads Threads are units of execution in a program Java programs start with one thread, which begins by executing the code in the main program Programs can create additional threads which are all operating simultaneously Programs which contain more than one thread are multithreaded programs Java GUI programs are multithreaded

Threads in Swing Programs There are three major types of threads used in swing programs: Initial threads execute initial application code The event dispatch thread handles all of the events for the GUI Worker threads executes time-consuming background tasks so that the user interface does not freeze while the task is being performed

The Event Dispatch Thread Executes code which handles GUI events (button presses, mouse movement, etc.) Most Swing object methods are not thread safe – invoking them from multiple threads risks consistency errors in memory that are hard to debug As a result, all GUI updating should be handled by this thread Jobs to be executed by this thread must be scheduled with the invokeLater or invokeAndWait methods of the javax.swing.SwingUtilities class

Initial Threads In standard Java applications, one initial thread starts the main method (for applets, the initial threads construct the applet and invoke its init and start methods) For Swing programs, the initial threads do not have much to do The main task is to initialize the GUI and schedule it to be executed by the event dispatch thread

Worker Threads Tasks can be performed by the event dispatch thread as long as they complete quickly If tasks executed by the event dispatch thread take too long, then the GUI becomes unresponsive to the user’s input To prevent this, worker threads are used for time consuming tasks, leaving the EDT to take care of the GUI events

So What Does Main Do? invokeLater This method needs an Runnable object as a parameter Runnable objects contain a run method which is executed when the object is used to create a thread Anonymous class: a class which is declared and instantiated at the same time. Used when the class is only needed once. new Runnable() { public void run() { mainFrame.setVisible(true); } } Initialize the GUI Jframe mainframe = createGUI(); Schedule it to be executed by the event dispatch thread SwingUtilities.invokeLater(); Schedule it to be executed by the event dispatch thread

Hello World Better package example01; import javax.swing.*; public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); } public static void main(String[] args) { JFrame mainframe = createGUI(); SwingUtilities.invokeLater(new Runnable() { public void run() { mainframe.setVisible(true); } }); } MainThread Create GUI Schedule for the EDT to make it visible E D T

Make it Even Better! public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); Instead of having the main program class “create” a JFrame… public class HelloWorld extends JFrame { Let the main program class actually “BE” a JFrame public class HelloWorld extends JFrame { private JLabel label; Objects in the frame should then be class variables so they are accessible from any method

package example01; import javax.swing.*; public class HelloWorld { public static JFrame createGUI() { JFrame frame = new JFrame("Hello World"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); } public static void main(String[] args) { JFrame mainframe = createGUI(); SwingUtilities.invokeLater(new Runnable() { public void run() { mainframe.setVisible(true); } }); } package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } Hello World Even Better

Where Did Main Go? We have two options: Option #1 Since this class is now a JFrame, main can be moved into a separate class In this new main class, instead of creating a “JFrame” object, you will need to create a “HelloWorldEvenBetter” object package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); }

Option #1 HelloWorldEvenBetter.java package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } MainApplication.java package example01; import javax.swing.*; public class MainApplication { public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new HelloWorldEvenBetter().setVisible(true); } }); }

Option #2 Any Java class can contain a main method – meaning that any class can be made to be “executable” It is preferred to do this, for the main GUI frame package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new HelloWorldEvenBetter().setVisible(true); } }); } HelloWorldEvenBetter.java

One More Revision The invokeLater method wants a Runnable object as a parameter We created an anonymous class with only a single (required) run method When you create an anonymous class in this manner, it can be replaced with a lambda expression instead Lambda expressions work like anonymous methods (a method without a name) new Runnable() { public void run() { new HelloWorldEvenBetter.setVisible(true); } () -> { new HelloWorldEvenBetter.setVisible(true); } Is the same as: So main becomes: SwingUtilities.invokeLater( () -> { new HelloWorldEvenBetter.setVisible(true); });

Final Version This is the final version of the “Hello World” GUI program package example01; import javax.swing.*; public class HelloWorldEvenBetter extends JFrame { private JLabel label; public HelloWorldEvenBetter() { initComponents(); setTitle("Hello World"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { label = new Jlabel("Hello World"); getContentPane().add(label); } public static void main(String [] args) { SwingUtilities.invokeLater( () -> { new HelloWorldEvenBetter().setVisible(true); }); } HelloWorldEvenBetter.java

Example #2 Demonstrates: Setting preferred sizes for objects Putting a menu bar in the frame Coloring the menu bar Adding a big colored label to the content pane Root Pane Layered Pane Content Pane Menu Bar JLabel

Things You Need To Know You need to create a JMenuBar object A Color object is needed to implement colors for various GUI items Initialize the Color object with the amount of red, green and blue you want in the color The amount is one byte for each == an integer from A Dimension object is needed to establish sizes Initialize with the width and the height, in pixels

Start with the Basic Template package example02; import java.awt.*; import javax.swing.*; public class TopLevelDemo extends JFrame { public TopLevelDemo() { initComponents(); setTitle("Top Level Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { } public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TopLevelDemo().setVisible(true); } }); } TopLevelDemo.java

Add Class Variables and Initialization Code private JMenuBar greenMenuBar; private JLabel yellowLabel; private void initComponents() { greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); setJMenuBar(greenMenuBar); getContentPane().add(yellowLabel); pack(); } TopLevelDemo greenMenuBar yellowLabel

Final Version This is the final version of the “TopLevelDemo” program package example02; import java.awt.*; import javax.swing.*; public class TopLevelDemo extends JFrame { private JMenuBar greenMenuBar; private JLabel yellowLabel; public TopLevelDemo() { initComponents(); setTitle("Top Level Demo"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); } private void initComponents() { greenMenuBar = new JMenuBar(); greenMenuBar.setOpaque(true); greenMenuBar.setBackground(new Color(154, 165, 127)); greenMenuBar.setPreferredSize(new Dimension(200, 20)); yellowLabel = new JLabel(); yellowLabel.setOpaque(true); yellowLabel.setBackground(new Color(248, 213, 131)); yellowLabel.setPreferredSize(new Dimension(200, 180)); setJMenuBar(greenMenuBar); getContentPane().add(yellowLabel); pack(); } public static void main(String [] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TopLevelDemo().setVisible(true); } }); }

Layout Managers Each container (by default) has a layout manager These objects determine the size and position of the components in the container Components in the container can provide suggestions about size and alignment, however the layout manager makes the final decision about how items are positioned There are four layout managers which are fairly simple to use Additional layout managers can be written by creating a class which implements the LayoutManager interface

Border Layout The default manager for all content panes (except JPanel) Has five areas for holding components: NORTH, SOUTH, EAST, WEST, CENTER All extra space is placed in the center Requires you to indicate in which you want components placed

Box Layout Puts components on a single row or column Components are not sized beyond their requested maximum size

Flow Layout Default manager for Jpanel objects Sets out components from left to right Starts new rows when necessary

Grid Layout Displays components in a grid Resizes components so they are all equal in size Components are added left to right, filling a row before moving on to another row When creating, you must specify the number of desired rows OR columns. The opposite value is automatically computed

Other Choices Grid Bag Layout A sophisticated layout manager with much more control over the grid Requires additional objects to help define the pacement of components Absolute Positioning Used when the layout manager is set to null Programmer must specify exact position and size for all components