Java GUI with Swing Part I Java How








































![import javax. swing. JFrame; public class Button. Demo. Test{ public static void main(String args[]){ import javax. swing. JFrame; public class Button. Demo. Test{ public static void main(String args[]){](https://slidetodoc.com/presentation_image_h2/6f389a9cbf3cbfdffd652579e59ce989/image-41.jpg)























- Slides: 64

Java GUI with Swing (Part I) Java – How to Program By Deitel & Deitel and http: //docs. oracle. com/javase/tutorial/u iswing/index. html

Swing and AWT • AWT (java. awt) and Swing (javax. swing) • AWT gives same look and Swing allows for different look • AWT is heavyweight and Swing is mostly lightweight

Top level container JApplet JDialog JFrame

• To appear on screen, every GUI component must be part of a containment hierarchy. • Each GUI component can be contained only once. • Each top-level container has a content pane that contains (directly or indirectly) the visible components in that top-level container's GUI. • 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.

Frame Menu Bar Content Pane with a yellow label


Top level containers java. lang. Object java. awt. Component java. awt. Container java. awt. Window java. awt. Frame javax. swing. JFrame

java. lang. Object java. awt. Component java. awt. Container java. awt. Window java. awt. Dialog javax. swing. JDialog

java. lang. Object java. awt. Component java. awt. Container java. awt. Panel java. applet. Applet javax. swing. JApplet

Swing Component hierarchy java. lang. Object java. awt. Component java. awt. Container javax. swing. JComponent

General purpose container JPanel JScroll. Pane JSplit. Pane JTabbed. Pane JTool. Bar

Special Purpose Container JInternal. Frame JLayered. Pane Root pane

Basic Controls JCheck. Box JCombo. Box JButton JList JRadio. Button JMenu

JSlider JSpinner JText. Field JPassword. Field

JColor. Chooser JEditor. Pane and JText. Pane

JFile. Chooser JTree

JTable

JText. Area

JProgress. Bar JSeparator JLabel JTool. Tip

How to Make Frames (Main Windows)

What is Frame? • is a top-level window with a title and a border. • The size of the frame includes any area designated for the border. • Applications with a GUI typically use at least one frame.

Creating and Showing Frames import java. awt. *; import java. awt. event. *; import javax. swing. *; /* Frame. Demo. java requires no other files. */ public class Frame. Demo { …. . public static void main(String[] args) { //Create and set up the window. JFrame frame = new JFrame("Frame. Demo"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); …… //Display the window. frame. pack(); frame. set. Visible(true); } …… }

The Frame API • Creating and Setting Up a Frame • Setting the Window Size and Location • Methods Related to the Root Pane

Creating and Setting Up a Frame JFrame() JFrame(String) Create a frame that is initially invisible. The String argument provides a title for the frame. set. Visible(bool) To make the frame visible, invoke set. Visible(true) on it.

void set. Default. Close. Operation(int) int get. Default. Close. Operation() Set or get operation that occurs when the user pushes the close button on this frame. Possible choices are: DO_NOTHING_ON_CLOSE HIDE_ON_CLOSE DISPOSE_ON_CLOSE EXIT_ON_CLOSE

void set. Icon. Image(Image) Image get. Icon. Image() Set or get the icon that represents the frame. Note that the argument is a java. awt. Image object, not a javax. swing. Image. Icon (or any other javax. swing. Icon implementation).

void set. Title(String) String get. Title() (in Frame) Set or get the frame's title.

Setting Window Size & Location void pack() (in Window) Size the window so that all its contents are at or above their preferred sizes.

void set. Size(int, int) void set. Size(Dimension) Dimension get. Size() (in Component) Set or get the total size of the window. The integer arguments to set. Size specify the width and height, respectively.

void set. Bounds(int, int) void set. Bounds(Rectangle) Rectangle get. Bounds() (in Component) Set or get the size and position of the window. For the integer version of set. Bounds, the window's upper left corner is at the x, y location specified by the first two arguments, and has the width and height specified by the last two arguments.

void set. Location(int, int) Point get. Location() (in Component) Set or get the location of the upper left corner of the window. The parameters are the x and y values, respectively.

void set. Location. Relative. To(C omponent) (in Window) Position the window so that it's centered over the specified component. If the argument is null, the window is centered onscreen. To properly center the window, you should invoke this method after the window's size has been set.

How to Use Buttons, Check Boxes, and Radio Buttons

java. lang. Object java. awt. Component java. awt. Container javax. swing. JComponent javax. swing. Abstract. Button

Class JButton JCheck. Box JRadio. Button JMenu. Item JCheck. Box. Menu. Item JRadio. Button. Menu. Item JToggle. Button Summary A common button. A check box button. One of a group of radio buttons. An item in a menu. A menu item that has a check box. A menu item that has a radio button. Implements toggle functionality inherited by JCheck. Box and JRadio. Button.

Basic Controls JCheck. Box JCombo. Box JButton JList JRadio. Button JMenu

How to use common button

import javax. swing. Abstract. Button; import javax. swing. JPanel; import javax. swing. Image. Icon; /* * Button. Demo. java requires the following files: * images/right. gif * images/middle. gif * images/left. gif */ public class Button. Demo extends JPanel { protected JButton b 1, b 2, b 3;

public Button. Demo() { Image. Icon left. Button. Icon = create. Image. Icon("images/right. gif"); Image. Icon middle. Button. Icon = create. Image. Icon("images/middle. gif"); Image. Icon right. Button. Icon = create. Image. Icon("images/left. gif"); b 1 = new JButton("Disable middle button", left. Button. Icon); b 1. set. Vertical. Text. Position(Abstract. Button. CENTER); b 1. set. Horizontal. Text. Position(Abstract. Button. LEADING); //aka LEFT, for left-to-right locales b 2 = new JButton("Middle button", middle. Button. Icon); b 2. set. Vertical. Text. Position(Abstract. Button. BOTTOM); b 2. set. Horizontal. Text. Position(Abstract. Button. CENTER); b 3 = new JButton("Enable middle button", right. Button. Icon); b 3. set. Vertical. Text. Position(Abstract. Button. CENTER); b 3. set. Horizontal. Text. Position(Abstract. Button. TRAILING); b 3. set. Enabled(false); // disable button b 1. set. Tool. Tip. Text("Click this button to disable the middle button. "); b 2. set. Tool. Tip. Text("This middle button does nothing when you click it. "); b 3. set. Tool. Tip. Text("Click this button to enable the middle button. "); //Add Components to this container, using the default Flow. Layout. add(b 1); add(b 2); add(b 3); }

/** Returns an Image. Icon, or null if the path was invalid. */ protected static Image. Icon create. Image. Icon(String path) { java. net. URL img. URL = Button. Demo. class. get. Resource(path); if (img. URL != null) { return new Image. Icon(img. URL); } else { System. err. println("Couldn't find file: " + path); return null; } } }
![import javax swing JFrame public class Button Demo Test public static void mainString args import javax. swing. JFrame; public class Button. Demo. Test{ public static void main(String args[]){](https://slidetodoc.com/presentation_image_h2/6f389a9cbf3cbfdffd652579e59ce989/image-41.jpg)
import javax. swing. JFrame; public class Button. Demo. Test{ public static void main(String args[]){ //Create and set up the window. JFrame frame = new JFrame("Top. Level. Demo"); frame. set. Default. Close. Operation(JFrame. EXIT_ON_CLOSE); //Create and set up the content pane. Button. Demo new. Content. Pane = new Button. Demo(); new. Content. Pane. set. Opaque(true); //content panes must be opaque frame. set. Content. Pane(new. Content. Pane); //Display the window. frame. pack(); frame. set. Visible(true); } }

Introduction to Event Handling

《interface》 Subject 《interface》 Observer register. Observer() remove. Observer() notify. Observer() update() Concrete. Subject Concrete. Observer register. Observer(){…} remove. Observer(){…} notify. Observer(){…} update(){…} // other methods get. State() set. State()

Java Event Handling Example Name in Design Pattern Subject Observer Concrete. Observer Attach() Notify() Actual Name in JButton Event Handling JButton Action. Listener The class that implements Action. Listener interface add. Action. Listener action. Performed

Basic concepts • Event – When users interact with a GUI component, the interaction is called event – Events drive the program to perform a task • Event source – the GUI component on which the event occurs • Event handler (listener) – The code that performs a task in response to an event • Event set up – The process of creating event handler class/object and registering the handler with event source • Event handling – The overall process of setting up event handling and responding to events

Event handling process • Event set up – Programmer write code to implement the event handler and register the event handler with a GUI component • Event handling – Java VM and GUI component works together responding to events

Set up Event Handling 1. Create an event handler (listener) class - The event handler class implements an appropriate event-listener interface. 2. Create an object of the above event handler class 3. Registering the event handler object with the event source (GUI component) – i. e. , when event occurs, a registered object of the event handler class will be notified.

GUI object (plain. JButton=new JButton(); ) listener. List Event Type (Action. Event) Class Button. Handler implements Action. Listener{ …. Public void action. Performed(…){ } …. } handler = new Button. Handler(); Event handler Interface (Action. Listener) Event handler class Event handler object plain. JButton. add. Action. Listener (handler); Add handler object to the event listener list of GUI object

Event Handling (delegation event model) 1. When an event occurs, Java VM sent event object to GUI component 2. The event object contains - event source, event type, and event id, etc 3. When GUI component receives event object – – – Identify the registered handler based on event type Identify the specific method for the registered handler based on event id Call the specific method to handle the event

Event Types & Listener Interfaces • Many different types of events • They are specified in java. awt. event • Event types specific to Swing are specified in javax. swing. event • For each event type, there is one or more corresponding event-listener interface • For each listener interface, there is one or more event handling methods.

Action Event and Action Listener • You implement an action listener to define what should be done when an user performs certain operation. • An action event occurs, whenever an action is performed by the user. - clicks a button, - chooses a menu item, - presses Enter in a text field. • When an action event occurs, JMV sends an Action. Event class object to event source.

Action. Event Class String get. Action. Command() Returns the string associated with this action. Most objects that can fire action events support a method called set. Action. Command that lets you set this string. int get. Modifiers() Returns an integer representing the modifier keys the user was pressing when the action event occurred. You can use the Action. Event-defined constants SHIFT_MASK, CTRL_MASK, META_MASK, and ALT_MASK to determine which keys were pressed. For example, if the user Shift-selects a menu item, then the following expression is nonzero: action. Event. get. Modifiers() & Action. Event. SHIFT_MASK Object get. Source() (in java. util. Event. Object) Returns the object that fires the event.

Action. Listener Interface public void action. Performed(Action. Event e) {. . . //code that reacts to the action. . . }

Write an Action Listener: • Declare an event handler class – – class either implements an Action. Listener interface or extends a class that implements an Action. Listener interface. public class My. Class implements Action. Listener { …… public void action. Performed(Action. Event e) {. . . //code that reacts to the action. . . } } • Register an instance of the event handler class on one or more components. some. Component. add. Action. Listener(instance. Of. My. Class);

Event handling with Nested Classes


// Fig. 11. 9: Text. Field. Frame. java // Demonstrating the JText. Field class. import java. awt. Flow. Layout; import java. awt. event. Action. Listener; import java. awt. event. Action. Event; import javax. swing. JFrame; import javax. swing. JText. Field; import javax. swing. JPassword. Field; import javax. swing. JOption. Pane; public class Text. Field. Frame extends JFrame { private JText. Field text. Field 1; // text field with set size private JText. Field text. Field 2; // text field constructed with text private JText. Field text. Field 3; // text field with text and size private JPassword. Field password. Field; // password field with text

// Text. Field. Frame constructor adds JText. Fields to JFrame public Text. Field. Frame() { super( "Testing JText. Field and JPassword. Field" ); set. Layout( new Flow. Layout() ); // set frame layout // construct textfield with 10 columns text. Field 1 = new JText. Field( 10 ); add( text. Field 1 ); // add text. Field 1 to JFrame // construct textfield with default text. Field 2 = new JText. Field( "Enter text here" ); add( text. Field 2 ); // add text. Field 2 to JFrame // construct textfield with default text and 21 columns text. Field 3 = new JText. Field( "Uneditable text field", 21 ); text. Field 3. set. Editable( false ); // disable editing add( text. Field 3 ); // add text. Field 3 to JFrame // construct passwordfield with default text password. Field = new JPassword. Field( "Hidden text" ); add(password. Field ); // add password. Field to JFrame

// create and register event handlers Text. Field. Handler handler = new Text. Field. Handler(); // create and register event handlers text. Field 1. add. Action. Listener( handler ); text. Field 2. add. Action. Listener( handler ); text. Field 3. add. Action. Listener( handler ); password. Field. add. Action. Listener( handler ); } // end Text. Field. Frame constructor

// private inner class for event handling private class Text. Field. Handler implements Action. Listener { // process textfield events public void action. Performed( Action. Event event ) { String string = ""; // declare string to display // user pressed Enter in JText. Field text. Field 1 if ( event. get. Source() == text. Field 1 ) string = String. format( "text. Field 1: %s", event. get. Action. Command() ); // user pressed Enter in JText. Field text. Field 2 else if ( event. get. Source() == text. Field 2 ) string = String. format( "text. Field 2: %s", event. get. Action. Command() ); // user pressed Enter in JText. Field text. Field 3 else if ( event. get. Source() == text. Field 3 ) string = String. format( "text. Field 3: %s", event. get. Action. Command() ); // user pressed Enter in JText. Field password. Field else if ( event. get. Source() == password. Field ) string = String. format( "password. Field: %s", new String( password. Field. get. Password() ) );

} // end class Text. Field. Frame // Fig. 11. 10: Text. Field. Test. java // Testing Text. Field. Frame. import javax. swing. JFrame; public class Text. Field. Test { public static void main( String args[] ) { Text. Field. Frame text. Field. Frame = new Text. Field. Frame(); text. Field. Frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE ); text. Field. Frame. set. Size( 325, 100 ); // set frame size text. Field. Frame. set. Visible( true ); // display frame } // end main } // end class Text. Field. Test

Event handling with Anonymous Inner Class

public class Button. Frame extends JFrame { private JButton plain. JButton; // button with just text // Button. Frame adds JButtons to JFrame public Button. Frame() { super( "Testing Buttons" ); set. Layout( new Flow. Layout() ); // set frame layout plain. JButton = new JButton( "Plain Button" ); // button with text add( plain. JButton ); // add plain. JButton to JFrame // create new Button. Handler for button event handling Button. Handler handler = new Button. Handler(); plain. JButton. add. Action. Listener( handler ); } // end Button. Frame constructor // inner class for button event handling private class Button. Handler implements Action. Listener { // handle button event public void action. Performed( Action. Event event ) { JOption. Pane. show. Message. Dialog( Button. Frame. this, String. format( "You pressed: %s", event. get. Action. Command() ) ); } // end method action. Performed } // end private inner class Button. Handler } // end class Button. Frame

public class Button. Frame extends JFrame { private JButton plain. JButton; // button with just text // Button. Frame adds JButtons to JFrame public Button. Frame() { super( "Testing Buttons" ); set. Layout( new Flow. Layout() ); // set frame layout plain. JButton = new JButton( "Plain Button" ); // button with text add( plain. JButton ); // add plain. JButton to JFrame //Use anonymous inner class plain. JButton. add. Action. Listener( new Action. Listener () // anonymous inner class { // handle button event public void action. Performed( Action. Event event ) { JOption. Pane. show. Message. Dialog( Button. Frame. this, String. format("You pressed: %s", event. get. Action. Command() ) ); } // end method action. Performed } // end of anonymous inner class ); // end of add } // end Button. Frame constructor } // end class Button. Frame