Chapter 14. More Swing

Similar documents
More Swing. Chapter 14. Chapter 14 1

Chapter 13 Lab Advanced GUI Applications Lab Objectives. Introduction. Task #1 Creating a Menu with Submenus

Window Interfaces Using Swing Objects

Chapter 13 Lab Advanced GUI Applications

Window Interfaces Using Swing Objects

More Swing. CS180 Recitation 12/(04,05)/08

Overview. Building Graphical User Interfaces. GUI Principles. AWT and Swing. Constructing GUIs Interface components GUI layout Event handling

Building Graphical User Interfaces. GUI Principles

PIC 20A GUI with swing

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Building Graphical User Interfaces. Overview

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CS 251 Intermediate Programming GUIs: Components and Layout

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Tool Kits, Swing. Overview. SMD158 Interactive Systems Spring Tool Kits in the Abstract. An overview of Swing/AWT

CSE 8B Intro to CS: Java

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Programming Languages and Techniques (CIS120e)

Layout. Dynamic layout, Swing and general layout strategies

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Introduction to the JAVA UI classes Advanced HCI IAT351

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

JAVA NOTES GRAPHICAL USER INTERFACES

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

GUI Programming: Swing and Event Handling

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Basicsof. JavaGUI and SWING

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Chapter 8. Java continued. CS Hugh Anderson s notes. Page number: 264 ALERT. MCQ test next week. This time. This place.

Java continued. Chapter 8 ALERT ALERT. Last week. MCQ test next week. This time. This place. Closed book. Assignment #2 is for groups of 3

Graphical User Interface (GUI)

Graphical User Interface (Part-3) Supplementary Material for CPSC 233

Swing II CHAPTER WINDOW LISTENERS 1034 Example: A Window Listener Inner Class 1036 The dispose Method 1040 The WindowAdapter Class 1041

Swing II Window Listeners Icons and Scroll Bars The Graphics Class Colors 1044

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Chapter 1 GUI Applications

Java Swing. Recitation 11/(20,21)/2008. CS 180 Department of Computer Science, Purdue University

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

Implementing Graphical User Interfaces

AP CS Unit 11: Graphics and Events

Laying Out Components. What is Widget Layout?

Graphical User Interface (Part-1) Supplementary Material for CPSC 233

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Event Driven Programming

Chapter 13. Applets and HTML. HTML Applets. Chapter 13 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

1.1 GUI. JFrame. import java.awt.*; import javax.swing.*; public class XXX extends JFrame { public XXX() { // XXX. init() main() public static

Graphical Interfaces

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

1005ICT Object Oriented Programming Lecture Notes

Programming graphics

Window Interfaces Using Swing. Chapter 12

CS 2113 Software Engineering

Swing from A to Z Some Simple Components. Preface

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Layout. Dynamic layout Layout design pattern Layout strategies

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

Layout. Dynamic layout Layout design pattern Layout strategies. 2.6 Layout 2

Part I: Learn Common Graphics Components

Part 3: Graphical User Interface (GUI) & Java Applets

Graphic User Interfaces. - GUI concepts - Swing - AWT

FORMAS DE IMPLEMENTAR LOS OYENTES. A).- El oyente en una clase independiente con el constructor con un argumento y usando el método getactioncommand.

Summary Chapter 25 GUI Components: Part 2

Systems Programming Graphical User Interfaces

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Class 16: The Swing Event Model

17 GUI API: Container 18 Hello world with a GUI 19 GUI API: JLabel 20 GUI API: Container: add() 21 Hello world with a GUI 22 GUI API: JFrame: setdefau

Jonathan Aldrich Charlie Garrod

GUI Components Continued EECS 448

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Dr. Hikmat A. M. AbdelJaber

Graphical User Interfaces. Swing. Jose Jesus García Rueda

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Graphical Interfaces

BASICS OF GRAPHICAL APPS

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Object Oriented Programming

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Graphical User Interface (GUI)

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Today. cisc3120-fall2012-parsons-lectiii.3 2

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Graphical User Interface (GUI)

Graphical User Interfaces in Java

Graphical User Interfaces. Comp 152

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Interfaces & Polymorphism part 2: Collections, Comparators, and More fun with Java graphics

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

YouTube Break.

CS 251 Intermediate Programming GUIs: Event Listeners

Final Exam CS 251, Intermediate Programming December 13, 2017

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

JLayeredPane. Depth Constants in JLayeredPane

Transcription:

Chapter 14 More Swing Menus Making GUIs Pretty (and More Functional) Box Containers and Box Layout Managers More on Events and Listeners Another Look at the Swing Class Hierarchy Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 1

Menus Three Swing classes used to put a menu in a program: AbstractButton» JMenuBar» JMenu» JMenuItem JButton JMenuItem JMenu Menu items behave in the same way as buttons Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 2

A GUI with a Menu JMenu memomenu = new JMenu("Memos"); JMenuItem m; m = new JMenuItem("Save Memo 1"); m.addactionlistener(this); memomenu.add(m); m = new JMenuItem("Save Memo 2"); m.addactionlistener(this); memomenu.add(m);... JMenuBar mbar = new JMenuBar(); mbar.add(memomenu); setjmenubar(mbar); Create a menu Create a menu item A menu item uses an action listener the same way a button does. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 3

A GUI with a Menu JMenu memomenu = new JMenu("Memos"); JMenuItem m; m = new JMenuItem("Save Memo 1"); m.addactionlistener(this); memomenu.add(m); m = new JMenuItem("Save Memo 2"); m.addactionlistener(this); memomenu.add(m);... JMenuBar mbar = new JMenuBar(); mbar.add(memomenu); setjmenubar(mbar); Each menu item is added to the menu. The menu is added to the menu bar. One way to add a menu bar to a JFrame Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 4

Nested Menus JMenu is a descendant of JMenuItem Every JMenu object is also a JMenuItem A JMenu can be a menu item in another menu This allows nested menus Clicking on a nested menu shows the items in the nested menu and allows them to be selected. AbstractButton JMenuItem JButton JMenu Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 5

Making GUIs Pretty (and More Functional) Adding Icons The JScrollPane Class for Scroll Bars Adding Borders Changing the Look and Feel Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 6

Using Icons Icons are (small) pictures Icons may be added to labels, buttons, and menu items. The ImageIcon class can be used to convert a picture to an icon: ImageIcon SmileyFaceIcon = new ImageIcon( smiley.gif ); The seticon method can be used to add an icon to a component: JLabel hellolabel = new JLabel( Hello ); ImageIcon dukewavingicon = new ImageIcon( duke_waving.gif ); hellolabel.seticon(dukewavingicon); Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 7

The JScrollPane Class for Scroll Bars A view port is used when not all information can be displayed on screen at once. Scroll bars move a view port around to show different parts of the information. JScrollPane is a class that can provide a view port with scroll bars. An example using JScrollPane with a JTextArea called thetext and a JPanel called textpanel: JScrollPane scrolledtext = new JScrollPane(theText); textpanel.add(scrolledtext); Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 8

Adding Borders A border is an area that frames a component. Swing provides several different types of borders:» BevelBorder makes component look raised or lowered» EtchedBorder similar to BevelBorder but can t set size» EmptyBorder extra space around the component» LineBorder colored border of a given thickness» MatteBorder similar to LineBorder but can adjust thickness on each side of the component An example of adding a bevel border to a button: testbutton.setborder(new BevelBorder(BevelBorder.LOWERED)); Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 9

Box Layout Manager Useful for a single column or single row of components Specify X_AXIS (horizontal) or Y_AXIS (vertical) layout as second parameter to constructor for layout manager Provides a means of separating components in a row or column» Strut allocates a fixed amount of space between two components» Glue allocates a variable amount of space between two components A Box container is a container that is automatically given a BoxLayout manager. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 10

Box Layout Versus Other Layouts Horizontal box layout is similar to flow layout. Vertical box layout is similar to grid layout with only one column. Big advantage of box layout is control over spacing using struts and glue. Note that it is possible to use struts and glue with other layout managers but they will probably not work as intended. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 11

Box Layout Demo Program Specifies a horizontal layout JPanel horizontalpanel = new JPanel(); horizontalpanel.setlayout( new BoxLayout(horizontalPanel, BoxLayout.X_AXIS)); Component horizontalstrut = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalpanel.add(horizontalstrut); JButton hstopbutton = new JButton("Red"); hstopbutton.addactionlistener(this); horizontalpanel.add(hstopbutton); Static method in Box class used to create a strut of a particular size for spacing Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 12

Struts and Glue invisible components used to add space between visible components horizontal strut:» programmer specifies width, which layout manager does not change vertical strut:» programmer specifies height, which layout manager does not change glue:» no specified size» can be added to layout to specify where extra space should go when container grows Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 13

Setting the Spacing Between Components To control spacing with layouts other than the Box layout, use sethgap and setvgap: public void sethgap(int hgap)» sets the horizontal gap between components» argument is size of gap in pixels public void setvgap(int vgap)» sets the vertical gap between components» argument is size of gap in pixels Can also use EmptyBorder in any layout manager which will add space as part of a component Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 14

The Box Container Class A Box object works like a panel with a BoxLayout manager. Created using static methods: Box horizontalbox = Box.createHorizontalBox(); Box verticalbox = Box.createVerticalBox(); Automatically given a BoxLayout manager when created» You should not use setlayout method with a box object. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 15

The CardLayout Manager Allows a set of views (components) to choose among» Only one view is visible at a time.» Can go through views in order or jump to any view.» Often the components added to a CardLayout will be panels. Each component added to a CardLayout has a string associated with it that works like a name: deckpanel.add("start", startcardpanel);» The string can be used later to display that component (or view): dealer.show(deckpanel, "start"); Need reference to layout manager to change views, so do not use anonymous object: deckpanel.add(new CardLayout()); legal but useless Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 16

CardLayoutDemo deckpanel = new JPanel(); dealer = new CardLayout(); deckpanel.setlayout(dealer);... deckpanel.add("start", startcardpanel);... deckpanel.add("green", greencardpanel);... deckpanel.add("red", redcardpanel);... dealer.show(deckpanel, "red");... dealer.next(deckpanel); Only one of these three panels will be visible at a time. will show redcardpanel if redcardpanel is currently displayed, will show startcardpanel Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 17

Inner Classes An inner class is a class defined within another class. Advantages: They make the outer class more self contained.» If WindowDestroyer is used, must make sure that class is available.» If InnerDestroyer (inner class version of WindowDestroyer) is used, it will always be available. Inner class has access to all instance variables and methods of outer class, including private ones. Avoid name conflicts.» You could have another (outer) class called InnerDestroyer and there would not be a conflict. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 18

The WindowListener Interface For a class to be a listener for window events, it must implement the WindowListener interface. By implementing the WindowListener interface, a window can be its own listener. The advantage of making a window its own listener is that it is easy to call methods from the listener since they are in the same object. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 19

The WindowListener Interface Implementation of the WindowListener interface requires these seven methods to be defined:» public void windowopened(windowevent e)» public void windowclosing(windowevent e)» public void windowclosed(windowevent e)» public void windowiconified(windowevent e)» public void windowdeiconified(windowevent e)» public void windowactivated(windowevent e)» public void windowdeactivated(windowevent e) If a method will be not be used, it should be defined with an empty body WindowAdapter is a class that implements all seven methods of the WindowListener with empty bodies. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 20

Programming the Close-Window Button The WindowListener interface can be used to program the close-window button. If the close-window button is not programmed, by default it will close the window but not exit the program. For a window that does not close when the close-window button is clicked, use a method call like this: setdefaultcloseoperation( WindowConstants.DO_NOTHING_ON_CLOSE); The CloseWindowDemo uses this method call When the close-window button is clicked, the program displays a confirmation dialog instead of closing the window. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 21

CloseWindowDemo Program public CloseWindowDemo() { setsize(width, HEIGHT); } setdefaultcloseoperation( WindowConstants.DO_NOTHING_ON_CLOSE); addwindowlistener(new InnerDestroyer()); settitle("close Window Demo"); Container contentpane = getcontentpane(); contentpane.setlayout(new BorderLayout());... Prevents window from closing so that user can confirm or cancel before window is closed. Constructor for the CloseWindowDemo class, which inherits from JFrame. Defined on next slide Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 22

CloseWindowDemo Program Definition of inner class used as listener for the CloseWindowDemo class. Inherits from WindowAdapter so it does not have to define all seven window event methods. private class InnerDestroyer extends WindowAdapter { public void windowclosing(windowevent e) } { } ConfirmWindow askwindow = new ConfirmWindow(); askwindow.setvisible(true); ConfirmWindow closes window and exits program if user confirms close. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 23

CloseWindowDemo Program public void actionperformed(actionevent e) { if (e.getactioncommand().equals("yes")) } actionperformed method from the ConfirmWindow inner class The main window will only be closed if the user clicks the Yes button in the ConfirmWindow System.exit(0); else if (e.getactioncommand().equals("no")) dispose(); //Destroys only the ConfirmWindow. else System.out.println("Error in Confirm Window."); Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 24

Changing Components A program can add or remove components after a GUI has been displayed, but that is beyond the scope of the book. Making components visible or not visible gives a similar effect. The setvisible method is used in the VisibleDemo program to make only one of the red and green labels visible at a time. (code on next slide) Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 25

Changing Components The actionperformed method from the VisibleDemo program public void actionperformed(actionevent e) { if (e.getactioncommand().equals( Red )) { colorpanel.setbackground(color.red); stoplabel.setvisible(false); golabel.setvisible(true); validate(); } Visibility changes won t... occur until the validate method is called. } There is similar code for when the Green button is pressed, which turns the background green and hides the go label. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 26

Another Look at the Swing Class Hierarchy JComponent Swing AbstractButton JLabel JMenuBar JButton JMenuItem JMenu Abstract Class Class All of the basic properties of JButton and JMenuItem are inherited from AbstractButton. JButton and JMenuItem are similar because they are derived from the same abstract class. Since AbstractButton is an abstract class, no objects of that class can be made. The purpose of the AbstractButton class is to provide a place for code that is common to JButton and JMenuItem and avoid repeated code. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 27

Another Look at the Swing Class Hierarchy JComponent Swing AbstractButton JLabel JMenuBar JMenuItem Abstract Class JButton Class JMenu JLabel and JButton inherit from a common ancestor, namely JComponent, so they have some similarities. Notice, however, that JLabel and JButton are not derived from the same class, even though they have a common ancestor. The hierarchy reflects the fact that JButton and JMenuItem are more similar than JLabel and JButton. Also notice that JMenu inherits from JMenuItem, so it can be used anywhere a JMenuItem can. This allows nested menus. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 28

Summary You can add icons to JButtons, JLabels, and JMenuItems. A JMenuBar can be added to a JFrame with the method setjmenubar or with the usual add method. Both buttons and menu items fire action events and so should have an ActionListener registered with them. You can use the class JScrollPane to add scroll bars to a text area. You can define a window listener class by having it implement the WindowListener interface. If you want a close-button to do something other than close the window, you must use SetDefaultCloseOperation. If you change the visibility of a component you should use the validate method to update the GUI. Chapter 14 Java: an Introduction to Computer Science & Programming - Walter Savitch 29