Programming with Java’s Swing API February 4, 2003 CMPS 109 - Advanced Programming Graphical User Interfaces.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Introduction to Swing Components Chapter 14. Part of the Java Foundation Classes (JFC) Provides a rich set of GUI components Used to create a Java program.
Graphical User Interfaces (Part IV)
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
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 Week 12 Graphical User Interfaces Chapter 11.
CC1007NI: Further Programming Week 5 Dhruba Sen Module Leader (Islington College)
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
Graphic User Interfaces Part 1. Typical GUI Screen from Microsoft Word What GUI “components” can you see? –Menus? Buttons? Labels? What else? –Anything.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
CS3 - AWT/Swing1 The Abstract Windowing Toolkit Since Java was first released, its user interface facilities have been a significant weakness –The Abstract.
Java Programming Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Intro to GUIs (Graphical User Interfaces) Section 2.5Intro. to GUIs: a GUI Greeter Section 3.7Graphical/Internet Java: Einstein's Equation.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Lesson 27: Introduction to the Java GUI. // helloworldbutton.java import java.awt.*; import javax.swing.*; class HelloButton{ public static void main.
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.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
Java GUIs and Graphics CNS Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
GUI Clients 1 Enterprise Applications CE00465-M Clients with Graphical User Interfaces.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
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.
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.
OOP (Java): GUI Intro/ OOP Objectives – –use an image viewer application to introduce Java's GUI features Semester 2,
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
Lec.10 (Chapter 8 & 9) GUI Jiang (Jen) ZHENG June 27 th, 2005.
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Swing Components. Introduction Swing – A set of GUI classes – Part of the Java's standard library –Much better than the previous library: AWT Abstract.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
1CS480: Graphical User Interfaces. Dario Salvucci, Drexel University. Lecture 3: Layout Basics.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lesson 28: More on the GUI button, frame and actions.
Objects First With Java A Practical Introduction Using BlueJ Building Graphical User Interfaces (GUIs) Week
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Java Swing What is swing? Swing is a ”Lightweight” GUI ToolKit for Java Different from AWT / SWT Toolkits for GUIs Few lines of code to produce GUI elements.
A Quick Java Swing Tutorial
GUIs and Events Rick Mercer.
A Quick Java Swing Tutorial
Ellen Walker Hiram College
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
GUIS: Graphical User Interfaces
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced Programming in Java
Graphical User Interface
Presentation transcript:

Programming with Java’s Swing API February 4, 2003 CMPS Advanced Programming Graphical User Interfaces

Does your program do what it is supposed to? If the program doesn’t work, there’s no point to using it. Is the program’s use easy to understand for its intended audience? If the people you are writing the program for don’t understand how it works, they can’t use it. Does the program perform at an acceptable speed? If it takes forever to run, people will not want to use it. Priorities

Interfaces are everywhere in programming Application Program Interface (API) Class interface Library interface User Interfaces (UIs) are how your program interacts with the outside world. Most UIs are bad. Programmers don’t have the training to create a good UI. Psychology is providing the framework for understanding what makes a good User Interface. Interfaces

Graphical User Interfaces (GUIs) provide the users with an easily understood metaphor for interacting with a computer. GUIs consist of “Windows” that are blocked off areas of the screen, and “Components” or “Widgets” within those Windows. Examples of Components: Labels, Buttons, Images, Text Entry boxes, Lists, Trees, Menus, etc. Graphical Interfaces

The Abstract Windowing Toolkit (AWT) was Java’s original GUI toolkit. It used “native” widgets. It was difficult to program. It did not support a wide range of widgets. Swing was introduced with Java 2 (the Java 1.2 API) It only used native windows, all other widgets were drawn “by hand”. Swing supports a wider range of widgets, and is easily extended. AWT and Swing

Swing has its own “Look and Feel” that is distinct from the “native” look and feel of the systems it runs on. Many companies have developed their own Look and Feel so that users can’t see the difference. Java Swing

import java.awt.*; import javax.swing.*; class HelloButton { public static void main( String[] args ) { JFrame frame = new JFrame( “Hello Button” ); Container pane = frame.getContentPane(); JButton hello = new JButton( “Hello, world!” ); pane.add( hello ); frame.pack(); frame.show(); } A Small Sample

You need to import both java.awt.* and javax.swing.* to get all the basic classes. What to import import java.awt.*; import javax.swing.*;...

Creating a JFrame gives you a “top level” container. “Top level” containers are backed by native UI components (usually Windows or Dialogs). The string passed to the constructor is the title of the window. Creating a JFrame... JFrame frame = new JFrame( “Hello Button” );...

You can’t add components directly to a JFrame. JFrame uses different layers (panes) to support various Swing features (Drag and Drop, ToolTips, etc). Instead, you must add to the frame’s Content Pane. Call getContentPane() to get the content pane. The Content Pane... Container pane = frame.getContentPane();...

Create another Swing component. In this case, a standard push-button is created with the label “Hello, World!”. This button doesn’t do anything when pushed. Call add() with the component as a parameter to add it to the frame’s content pane. Adding content... JButton hello = new JButton( “Hello, world!” ); pane.add( hello );...

pack() will resize the frame to the minimum size needed to display the items in the content pane. Calling show() will show the JFrame. You must set the size of the frame (directly or with pack()) before you show the frame. Resizing and showing... frame.pack(); frame.show();...

When you close the window, you might notice that your program does not quit. When the first Swing component is created, a new Thread is created also. Threads allow a single program to do two things “at the same time.” In Swing’s case, the new thread is created to track and capture events (mouse, keyboard, etc). We’ll cover how to handle quitting and threads in Swing a little later. Quitting your program?

Swing Provides the following Components: Swing Components Buttons: JButton JCheckBox JRadioButton Containers: JPanel JFrame JDialog Lists: JList JTree JTable Menus: JMenuBar JMenu JMenuItem Miscellaneous: JFileChooser JCollerChooser JToolTip Organizers: JSplitPane JTabbedPane JToolBar Ranged Controls: JSpinner JSlider JProgressBar Scrolling: JScrollBar JScrollPane Text: JTextArea JTextField JLabel

Threads are a way of separating the work that a program does into multiple execution paths. They are sometimes compared to mini-programs. In Swing, the Event thread is an infinite loop. You have to call System.exit( 0 ); to actually quit. The Event Thread

Each pass through the event loop, Swing looks for mouse movements, mouse button presses, keyboard presses, etc. If an event is found, Swing passes any appropriate data to the component most directly affected by the event. Keyboard events go to the component that has “focus”. Mouse events go to the component under the mouse (if any). The Event Thread

You can “listen” for events in components you create by adding “listeners”. Swing defines a number of listener interfaces: Listening for Events java.awt.eventjavax.swing.event ActionListenerChangeListener MouseListenerDocumentListener MouseMotionListenerTableModelListener WindowListenerTreeModelListener ItemListener

You can tell what kind of events a component can receive by looking for functions of the form addXYZListener(), and examining the type of listener the function expects as a parameter. addActionListener() is used by a number of components and needs a parameter of ActionEventListener. Listening for Events

Any class can implement an event listener interface. Named inner classes are usually the best way to implement event listeners. Inner classes have direct access to the data stored in the outer class. You never have to wonder where the events are handled. Most event listeners are short functions (5 lines or less). Event Listeners

Never use anonymous classes to implement an event listener. Do not try to do long processing in an event listener, or a function called by a listener. Do not try to share listeners between components. Event Listener Warnings

import java.awt.*; import javax.swing.*; import java.awt.event.*; class HelloButton { public static void main( String[] args ) { new HelloButton(); } HelloButton() { JButton hello = new JButton( “Hello, world!” ); hello.addActionListener( new HelloButtonListener() ); JFrame frame = new JFrame( “Hello Button” ); Container pane = frame.getContentPane(); pane.add( hello ); frame.pack(); frame.show(); } A Sample Listener

private class HelloButtonListener implements ActionListener { public void actionPerformed( ActionEvent e ) { System.out.println( “The event was: “ + e ); } A Sample Listener The event was: java.awt.event.ActionEvent[ACTION_PERFORMED,cmd=Hello, world!] on javax.swing.JButton[,0,0,141x27,layout=javax.swing.OverlayLayout,alignm entX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$Com javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintB order=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverIco n=,rolloverSelectedIcon=,selectedIcon=,text=Hello, world!,defaultCapable=true]

The code to create the UI is now in the class constructor. Inner classes that are not static have to be created by class functions that are not static. The components that are added to the frame are created and configured before the frame is even created. Organizing the code to deal with only one component at a time makes it easier to read and change. Changes in the example

Some listeners have many events they can listen for. MouseListener (5 events) WindowListener (7 events) Adapters are sometimes provided for these listeners. Implement the listener interface with empty functions. You can subclass the adapter if you don’t want to implement the entire listener. Just override the functions you want to work with. Adapters vs. Listeners

import java.awt.*; import javax.swing.*; import java.awt.event.*; class HelloButton { public static void main( String[] args ) { new HelloButton(); } HelloButton() { JButton hello = new JButton( “Hello, world!” ); hello.addActionListener( new HelloButtonListener() ); JFrame frame = new JFrame( “Hello Button” ); frame.addWindowListener( new HelloButtonWindowListener() ); frame.getContentPane().add( hello ); frame.pack(); frame.show(); } Quitting Example

private class HelloButtonListener implements ActionListener { public void actionPerformed( ActionEvent e ) { System.out.println( “The event was: “ + e ); } private class HelloButtonWindowListener extends WindowAdapter { public void windowClosed( WindowEvent e ) { System.out.println( “Goodbye!” ); System.exit( 0 ); } Quitting Example

A Layout Manager determines where each component should be placed in the window or the container. The book has excellent examples for many of the common layout managers: FlowLayout places components in the window from left to right, like a word processor. GridLayout is like a table, all components are the same size. Border Layout splits the area into 5 predefined spaces like a compass. Component Layout

JPanel is an empty component that does not have any visual representation. JPanels are used to split one container into smaller (more manageable) areas. Each JPanel has its own layout manager. You can assign a GridLayout to the JFrame, and put a JPanel with a BorderLayout in each cell. JPanel and Nested Containers

JPanelExample() { JFrame frame = new JFrame( “JPanel Example” ); frame.getContentPane().setLayout( new GridLayout( 2, 2 ) ); for( int i = 0; i < 2; i ++ ) { for( int j = 0; j < 2; j++ ) { JPanel p = new JPanel(); p.setLayout( new BorderLayout() ); p.add( new JButton( “North” ), BorderLayout.NORTH ); p.add( new JButton( “South” ), BorderLayout.SOUTH ); p.add( new JButton( “East” ), BorderLayout.EAST ); p.add( new JButton( “West” ), BorderLayout.WEST ); p.add( new JButton( “Center” ), BorderLayout.CENTER ); frame.getContentPane().add( p ); } frame.pack(); frame.show(); } Nested Container Example

BoxLayout is an easy to use layout manager that allows you to create complex containment schemes. It is more flexible than the other managers, but only slightly more complex than the FlowLayout. It requires you to use nested containers. BoxLayout

BoxLayoutExample() { JPanel p1 = new JPanel(); p1.setLayout( new BoxLayout( p1, BoxLayout.X_AXIS ) ); p1.add( Box.createHorizontalGlue() ); p1.add( new JButton( “Right Aligned” ) ); JPanel p2 = new JPanel(); p2.setLayout( new BoxLayout( p2, BoxLayout.X_AXIS ) ); p2.add( Box.createHorizontalGlue() ); p2.add( new JButton( “Center Aligned” ) ); p2.add( Box.createHorizontalGlue() ); JFrame frame = new JFrame( “JPanel Example” ); frame.getContentPane().setLayout( new BoxLayout( frame.getContentPane(), BoxLayout.Y_AXIS ) ); frame.getContentPane().add( p1 ); frame.getContentPane().add( Box.createVerticalStrut( 20 ) ); frame.getContentPane().add( p2 ); frame.pack(); frame.show(); } BoxLayout Example

You can set three size attributes of Swing Components: Minimum, Preferred, and Maximum Unlike most layout managers, BoxLayout respects the size attributes of its components. You get the a lot of flexibility with only a few functions. Why BoxLayout is a better layout

BorderFactory allows you to create borders for JComponent descendants (most of Swing). Call setBorder( BorderFactory.createXYZBorder() ); Uses of Borders: Excellent for debugging layout issues when you have nested JPanels and resize problems. Empty borders can be used to create extra spacing around components where nothing is drawn. Compound borders can be used to stack borders on top of each other (for example, an empty area of 12 pixels on all sides, and then an etched border, or another compound border). Borders

JTextField is a simple, single line text entry area. JTextArea allows multi-line input, but is much more complex. Text Input with Swing

private JTextField textField; private JLabel echoLabel; TextFieldExample() { textField = new JTextField( “Enter text here...” ); echoLabel = new JLabel( “...it will echo here.” ); JFrame frame = new JFrame( “Text Field Example” ); frame.getContentPane().setLayout( new GridLayout( 2, 1 ) ); frame.getContentPane().add( textField ); frame.getContentPane().add( echoLabel ); frame.pack(); frame.show(); } private class TextFieldListener implements ActionListener { public void actionPerformed( ActionEvent e ) { echoLabel.setText( textField.getText() ); } Text Input Example

JOptionPane allows you to create simple dialog boxes: showConfirmDialog() presents the user with up to three choices: Yes, No, and Cancel. showInputDialog() gives the user a question and a text field to enter input. showMessageDialog() is great for reporting errors (invalid input) and simple messages. Each function has multiple versions, with varying degrees of configuration. JOptionPane

JFrame and JDialog both provide the setJMenuBar() function to specify the menu bar for that window. JMenuBar provides an add() function to add JMenus. JMenu provides an add() function for JMenuItems, Strings, and Components. JMenus can be added to other JMenus. Menu bars and Menus

private JFrame mbeFrame; MenuBarExample() { mbeFrame = new JFrame( “Text Field Example” ); mbeFrame.setJMenuBar( makeMenuBar() ); mbeFrame.getContentPane().add( new JLabel( “Other Stuff Here.” ) ); mbeFrame.pack(); mbeFrame.show(); } private class QuitItemListener implements ActionListener { public void actionPerformed( ActionEvent e ) { if( JOptionPane.showConfirmDialog( mbeFrame, “Do you want to quit?”, “Confirm Quit”, JOptionPane.YES_NO_OPTION ) == JOptionPane.YES_OPTION ) { System.exit( 0 ); } Menu Bar Example

private JMenuBar makeMenuBar() { JMenuItem quitItem = new JMenuItem( “Quit” ); quitItem.addActionListener( new QuitItemListener() ); JMenu fileMenu = new JMenu( “File” ); fileMenu.add( new JMenuItem( “Item 1” ) ); fileMenu.add( “Item 2” ); fileMenu.addSeparator(); JMenu fontMenu = new JMenu( “Font” ); fontMenu.add( “Times” ); fontMenu.add( “Courier” ); fontMenu.add( “Script” ); JMenu editMenu = new JMenu( “Edit” ); editMenu.add( “Undo” ); editMenu.addSeparator(); editMenu.add( fontMenu ); JMenuBar mbar = new JMenuBar(); mbar.add( fileMenu ); mbar.add( editMenu ); return( mbar ); } Menu Bar Example

Demonstrations and Questions