Lecture 08 Abstract Windows Toolkit AWT and Swing
Lecture 08 Abstract Windows Toolkit (AWT) and Swing Components JAVA Jaeki Song
Outline • • • JAVA GUI Interface JAVA Graphics API Event Handling Layout Managers JComponents Jaeki Song
GUI Interface • Web-based application use a graphical user interface (GUI) • The graphical components are bundled in a library known as the Abstract Window Toolkit (AWT) – Mapped to the platform-specific components – Heavyweight components JAVA Jaeki Song
Why swing? • The appearance and how the user interacts with the program are known as that program’s look and feel. • javax. swing API makes the look and feel of GUI the same across platforms (lightweight component) JAVA Jaeki Song
GUI java. lang. Object java. awt. Component java. lang. Container java. swing. JComponent JAVA Jaeki Song
The Java Graphics API AWTEvent Classes in the java. awt package Layout. Manager Font Heavyweight Font. Metrics Object Color Panel Applet JApplet Window Frame JFrame Dialog JDialog Graphics Component Container * JComponent Swing Components in the javax. swing package Lightweight JAVA Jaeki Song
Java Graphics API • Component – A superclass of all user interface classes • Container – Used to group components • A layout manager is used to position and place components in a container in the desired location and style • JComponent – A super class of all the lightweight • JFrame – This is a window nor contained inside another window – It is a container that holds another Swing user-interface components JAVA Jaeki Song
Java Graphics API • JDialog – A popup window or message box generally used as a temporary window to receive additional information from the user or to provide notification that an event has occurred • JApplet – A subclass of Applet – You must extend JApplet to create a Swing-based Java Applet • JPanel – An invisible container that holds user-interface components – Panel can be nested JAVA Jaeki Song
Java Graphics API • Graphics – An abstract class that provides a graphical context for drawing lines and simple shapes • Color – A class deals with the colors of graphics components • Font – Usef for drawings in Graphics • Font. Metrics – An abstract class used to get the properties of the fonts used in drawings JAVA Jaeki Song
Graphic Classes Classification • Container classes – JFrame, JPanel, and JApplet • Component classes – Subclasses of JComponent • JButton, JText. Field, JText. Area, JCombo. Box, JList, JRadio. Button, and JMenu • Helper classes – Classes used by components and containers to draw and place objects • Graphics, Color, Font. Metrics, Dimension, and Layout Managers JAVA Jaeki Song
JComponent. JCheck. Box. Menu. Item Abstract. Button JMenu. Item JMenu JButton . JRadio. Button. Menu. Item . JToggle. Button JCheck. Box . JEditor. Pane JComponent. JText. Component . JText. Field JRadio. Button . JPassword. Field . JText. Area . JLabel JAVA . JList . JCombo. Box . JMenu. Bar . JPanel . JOption. Pane . JScroll. Bar . JScroll. Pane . JPopup. Menu . JSeparator . JSlider . JTabbed. Pane . JRoot. Pane . JProgress. Bar . JTool. Bar . JSplit. Pane . JTable . JTree . JColor. Chooser . JInternal. Frame . JTool. Tip . JLayered. Pane . JTable. Header . JFile. Chooser Jaeki Song
Frames • Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java graphical applications. • The Frame class can be used to create windows. JAVA Jaeki Song
JFrame • Two constructors public JFrame ( ) àCreates an untitled JFrame object public JFrame( String title) àCreate a JFrame object with a specific title • JFrame Methods • set. Title (String) JFrame my. Frame = new JFrame( ) this. set. Title (“ISQS 6337”); or set. Title (“ISQS 6337); • set. Size (int, int): Specify the frame size • set. Size (Dimension): • sets a JFrame’s size using a Dimension class by calling Dimension(int, int) constructor that creates the object representing the specified width and height arguments • String get. Title( ) • Returns a JFrame’s title JAVA Jaeki Song
JFrame • set. Visible (true) – The frame is not visible until set. Visible (true) method is applied • boolean is. Resizable( ) – Returns true or false to indicate whether the Frame is resizable • set. Default. Close. Operation (Jframe. EXIT_ON_CLOSE) – Tells the program to terminate when the frame is closed JAVA Jaeki Song
Example: Creating JFrame import javax. swing. *; public class My. Frame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame. set. Size(400, 300); frame. set. Visible(true); frame. set. Default. Close. Operation( JFrame. EXIT_ON_CLOSE); } } JAVA Jaeki Song
Creating Frame • By default, a frame is displayed in the upper-left corner of the screen. – To display a frame at a specified location, you can use the set. Location(x, y) method in the JFrame class. This method places the upperleft corner of a frame at location (x, y). JAVA Jaeki Song
Centering Frames Screen (x, y) Frame frame. Height screen. Height frame. Width screen. Width JAVA Jaeki Song
Centering Frames • Toolkit class – the abstract superclass of all actual implementations of the AWT – get. Screen. Size( ) • Can be used to obtain screen’s width and height • Dimension class – Encapsulates the width and height of a component – get. Size method • Get the size of Dimension object • Return dimension of the object • JFrame – set. Location (x, y) JAVA Jaeki Song
Example • Center. Frame JAVA Jaeki Song
Event-Driven Programming • An event can be defined as a type of signal to the program that something has happened. – The event is generated by external user actions such as mouse movements, mouse button clicks, and keystrokes, or by the operating system, such as a timer • The GUI component on which an event is generated is called the source object – E. g. • A button is the source object for a clicking-button action event JAVA Jaeki Song
Event Classes JAVA Jaeki Song
Selected User Actions User Action Clicked on a button Changed text Double-clicked on a list item Selected or deselected an item with a single click Selected or deselected an item JAVA Source Object Event Type Generated JButton Action. Event JText. Component Text. Event JList Action. Event JList Item. Event JCombo. Box Item. Event Jaeki Song
Event Handling Model • GUI event information is stored in an object of a class that extends AWTEvent • A program performs two key tasks – Event listener • An object of a class that implements one or more the event-listener interface from package java. awt. event – Event handler • A method that is automatically called in response to a particular type of event JAVA Jaeki Song
Event Handling Model • Each event-listener interface specifies one or more event handling methods that must be defined in the class that implements the event-listener interface • The use of event listeners is known as the delegation event model JAVA Jaeki Song
The Delegation Model JAVA Jaeki Song
Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers) Action. Event Item. Event Window. Event Action. Listener Item. Listener Window. Listener action. Performed(Action. Event) item. State. Changed(Item. Event) window. Closing(Window. Event) window. Opened(Window. Event) window. Iconified(Window. Event) window. Deiconified(Window. Event) window. Closed(Window. Event) window. Activated(Window. Event) window. Deactivated(Window. Event) JAVA Jaeki Song
Inner Class • Classes can be defined inside other classes • Inner classes are used mainly in event handling Public class A extends B { public class Action. Event. Handler implements Action. Lister{ public void action. Performed ( Action. Event e) { } } } • Inner classes with names have the file name Outer. Class. Name$Inner. Class. Name. class JAVA Jaeki Song
Anonymous Inner Class • Anonymous inner class (class without a name) • Anonymous inner class have the file name Outer. Class. Name$#. class – # starts at 1 and is incremented for each anonymous inner class encountered during compilation Window. add. Window. Listner( new Window. Adapter( ) { public void window. Closing( Window. Event e) { System. exit(0); } } ); JAVA Jaeki Song
JLabel • A subclass of Jcomponent • A label is a display area for a short text, an image, or both. The non-default constructors for labels are as follows: JLabel(String text, int horizontal. Alignment) JLabel(String text) JLabel(Icon icon, int horizontal. Alignment) JAVA Jaeki Song
Text Components • Use text component when you want to both display and input information – JText. Field • Allows only a single line of text – JText. Area • Allows multiple lines of text JAVA Jaeki Song
JText. Field • A text field is an input area where the user can type in characters. – Text fields are useful in that they enable the user to enter in variable data (such as a name or a description). • A text field can display information like a label JAVA Jaeki Song
JText. Field Constructors • JText. Field(int columns) – Creates an empty text field with the specified number of columns. • JText. Field txt. Name = new JText. Field (20); • JText. Field(String text) – Creates a text field initialized with the specified text. • JText. Field(String text, int columns) – Creates a text field initialized with the specified text and the column size. • JText. Field (String, int maximum. Number. Charaters) JAVA Jaeki Song
JText. Field Methods • get. Text() – Returns the string from the text field. • set. Text(String text) – Puts the given string in the text field. • set. Editable(boolean editable) – Enables or disables the text field to be edited. By default, editable is true. • set. Columns(int) – Sets the number of columns in this text field. The length of the text field is changeable. JAVA Jaeki Song
JText. Area • If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JText. Area, which enables the user to enter multiple lines of text. JAVA Jaeki Song
JText. Area Constructors • JText. Area( ) – Default constructor • Create an empty text area • JText. Area(int rows, int columns) – Creates a text area with the specified number of rows and columns. • JText. Area(String s, int rows, int columns) – Creates a text area with the initial text and the number of rows and columns specified. JAVA Jaeki Song
JText. Area Method • Append method – Allows to add information to the end of the string in a text area – Use append method to build your output as the information becomes available to create multiple lines of output • General Format component. Name. append(String); • Example txa. Inovice. append(“Sold to: ” + str. Name); JAVA Jaeki Song
Container • The onscreen display area has a content pane to which the GUI components must be attached so they can be displayed at execution time • The content pane is an object of class Container from the java. awt package Container c = get. Content. Pane(); Declares Container reference c and assigns it the result of a call to Method get. Content. Pane returns a content pane That can be used to attach GUI components JAVA Jaeki Song
JPanel • Panels act as smaller containers for grouping user interface components JPanel p = new JPanel(); • Adding component to a JPanel – add method • E. g. – add(Component. Name); JAVA Jaeki Song
JButton • A button is a component that triggers an action event when clicked. The following are JButton non-default constructors: JButton(String text) JButton(String text, Icon icon) JButton(Icon icon) • All button types are subclasses of Abstract. Button from javax. swing package – Button types • Command buttons, check boxes, and radio buttons • A command button gegnerates an Action. Event – When the user clicks the button with the mouse JAVA Jaeki Song
Responding to JButton Event public void action. Performed(Action. Event e) { // Get the button label Joption. Pane. show. Message. Dialog (null, “You pressed: ”+ e. get. Action. Commnad() ); } JAVA Jaeki Song
Layout Managers • Java’s layout managers provide a level of abstraction to automatically map your user interface on all windowing systems. • The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container. – – – JAVA Flow. Layout Grid. Layout Border. Layout Card. Layout Grid. Bag. Layout Jaeki Song
Flow. Layout Manager • The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started. • Flow. Layout Constructors – public Flow. Layout(int align, int h. Gap, int v. Gap) • Constructs a new Flow. Layout with a specified alignment, horizontal gap, and vertical gap. The gaps are the distances in pixel between components. – public Flow. Layout(int alignment) • Constructs a new Flow. Layout with a specified alignment and a default gap of five pixels for both horizontal and vertical. – public Flow. Layout() • Constructs a new Flow. Layout with a default center alignment and a default gap of five pixels for both horizontal and vertical. JAVA Jaeki Song
Border. Layout Manager • The Border. Layout manager divides the window into five areas: East, South, West, North, and Center. • Components are added to a Border. Layout – add(Component, constraint), where constraint is Border. Layout. East, Border. Layout. South, Border. Layout. West", Border. Layout. North", or Border. Layout. Center. JAVA Jaeki Song
Grid. Layout Manager • The Grid. Layout manager arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor. The components are placed in the grid from left to right starting with the first row, then the second, and so on. JAVA Jaeki Song
Grid. Layout Constructors • public Grid. Layout(int rows, int columns) – Constructs a new Grid. Layout with the specified number of rows and columns. • public Grid. Layout(int rows, int columns, int h. Gap, int v. Gap) – Constructs a new Grid. Layout with the specified number of rows and columns, along with specified horizontal and vertical gaps between components. JAVA Jaeki Song
Example • • JAVA Example 3: Tax Systems Example 4: Inventory Systems Example 5: Add List Example 6: Car Payment System Jaeki Song
JCheck. Box • A check box is a component that enables the user to toggle a choice on or off, like a light switch. – JCheck. Box constructors JCheck. Box(), JCheck. Box(String text, boolean selected), JCheck. Box(Icon icon), JCheck. Box(String text, Icon icon) JCheck. Box(String text, Icon icon, boolean selected) JAVA Jaeki Song
JCheck. Box • JCheck. Box Methods – set. Label (String Label) – get. Label – void set. State (boolean condition) • Sets the JCheck. Box state to true for checked or false for unchecked – boolean get. State • Requires using Item. Listner – Provides for objects whose states change from true of false – Requires item. State. Changed( ) method • Example 7: Dental Application JAVA Jaeki Song
JRadio. Button • Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time. – JRadio. Button constructors JRadio. Button(), JRadio. Button(String text) JRadio. Button(String text, boolean selected), JRadio. Button(Icon icon) JRadio. Button(String text, Icon icon, boolean selected) • Example 8: JRadio. Button JAVA Jaeki Song
JCombo. Box • A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value. To create a choice, use its default constructor: JCombo. Box() • Add items to the list with the add. Item( ) method JCombo. Box ( ) my. Choice = new JCombo. Box ( ); my. Choice. add. Item (“English”); my. Choice. add. Item (“Math”); JAVA Jaeki Song
JCombo. Box • JCombo. Box class method – String get. Item. At (int) : Returns the text of the list item at the index position specified by the integer argument – String get. Selected. Item( ): returns the text of the currently selected item – Int get. Item. Count( ): returns the number of items in the list – Int get. Selected. Index( ): returns the item in the list that matches the given item – void set. Maximum. Row. Count (int): sets the maximum number of combo box rows that are displayed at one time JAVA Jaeki Song
JCombo. Box • Treat items as an array – Use the get. Selected. Index( ) method to determine the list position of the currently selected item – E. g. String course [ ] = { “English”, “History”, “Math”} int choice = my. Choice. get. Selected. Index( ); • Example 09: JCombo. Box JAVA Jaeki Song
JScroll. Pane • When components in a Swing GUI are bigger than the area available to display them, you can add a scroll pane container • Common to add a JText. Area component to scroll pane container – It allows you to use both multiple rows and columns • Constructors – JScroll. Pane( ) • Creates where both horizontal and vertical scrollbars when needed – JScroll. Pane(Component) • Creates a JScroll. Pane that displays the contents of the specified component • E. g JText. Area output = new JText. Area( )’ JScroll. Pane scroll = new JScroll. Pane (output); JAVA Jaeki Song
JScroll. Pane • The horizontal and vertical scrollbars will appear if they are needed – User control of the horizontal and vertical scrollbar configuration is achieved by using class variable of the Scroll. Pane. Constants class. • • • HORIZONTAL_SCROLLBAR_AS_NEEDED HORIZONTAL_SCROLLBAR_ALWAYS HORIZONTAL_SCROLLBAR_NEVER VERTICAL_SCROLLBAR_AS_NEEDED VERTICAL_SCROLLBAR_ALWAYS JText. Area output = new JText. Area (10, 40); JScroll. Pane my. Scroll = new JScroll. Pane (output, VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBASR_NEVER); JAVA Jaeki Song
JTool. Bars • A swing GUI can be designed so that a user can move a toolbar from one section of a GUI to another section – This type of a toolbar is called a dockable toolbar • The process that allows you to move and then attach the toolbar is called docking java. lang. Object java. awt. Container javax. swing. JComponent javax. swing. JTool. Bar JAVA Jaeki Song
JTool. Bar • Constructor – JTool. Bar( ) • Creates a new toolbar that will line up components in a horizontal direction – JTool. Bar( int) • Creates a new toolbar with a specified orientation of horizontal or vertical – You can use the HORIZONTAL and VERTICAL constants from the Swing. Constants class to explicitly set the orientation – E. g. JTool. Bar my. Bar = new JTool. Bar (Swing. Constants. VERTICAL); • Example 10: JTool. Bar JAVA Jaeki Song
JList • A list is a component that enables you to choose one or more items • JList is the Swing component and functionally it is similar to JCheck. Box and JRadio. Button, but the selectable items are placed in a list and are chosen by clikcing on the items themselves • Example 11: JList JAVA Jaeki Song
Menus • Java provides several classes—JMenu. Bar, JMenu. Item, JCheck. Box. Menu. Item, and JRadio. Button. Menu. Item —to implement menus in a frame • A JFrame or JApplet can hold a menu bar to which the pull-down menus are attached. Menus consist of menu items that the user can select (or toggle on or off). Menu bars can be viewed as a structure to support menus. JAVA Jaeki Song
Menu Demo JAVA Jaeki Song
The JMenu. Bar Class • A menu bar holds menus; the menu bar can only be added to a frame. Following is the code to create and add a JMenu. Bar to a frame: JFrame f = new JFrame(); f. set. Size(300, 200); f. set. Visible(true); JMenu. Bar mb = new JMenu. Bar(); f. set. JMenu. Bar(mb); JAVA Jaeki Song
The Menu Class • You attach menus onto a JMenu. Bar. The following code creates two menus, File and Help, and adds them to the JMenu. Bar mb: JMenu file. Menu = new JMenu("File"); JMenu help. Menu = new JMenu("Help"); mb. add(file. Menu); mb. add(help. Menu); JAVA Jaeki Song
The JMenu. Item Class • You add menu items on a menu. The following code adds menu items and item separators in menu file. Menu: file. Menu. add(new JAVA JMenu. Item("new")); JMenu. Item("open")); JMenu. Item("-")); JMenu. Item("print")); JMenu. Item("exit")); JMenu. Item("-")); Jaeki Song
Submenus • You can add submenus into menu items. The following code adds the submenus “Unix, ” “NT, ” and “Win 95” into the menu item “Software. ” JMenu software. Help. Sub. Menu = new JMenu("Software"); JMenu hardware. Help. Sub. Menu = new JMenu("Hardware"); help. Menu. add(software. Help. Sub. Menu); help. Menu. add(hardware. Help. Sub. Menu); software. Help. Sub. Menu. add(new JMenu. Item("Unix")); software. Help. Sub. Menu. add(new JMenu. Item("NT")); software. Help. Sub. Menu. add(new JMenu. Item("Win 95")); JAVA Jaeki Song
Submenu Demo Example 12: JMemu JAVA Jaeki Song
- Slides: 64