Java GUI Basics

Objectives
•  •  •  •  •  •  •  •  • 
CSE UOWD

Introduction to java GUI basics To distinguish between Swing and AWT To describe the Java GUI API hierarchy To create user interfaces using frames, panels, and simple GUI components To understand the role of layout managers To use the FlowLayout, GridLayout, and BorderLayout managers to layout components in a container To use JPanel as subcontainers To specify colors and fonts using the Color and Font classes To apply common features such as borders, tool tips, fonts, and colors on Swing components
CSCI 213: Java GUI Spring 2013

2

Graphical user interface (GUI)
•  Presents a user-friendly mechanism for interacting with an application •  Often contains title bar, menu bar containing menus, buttons and combo boxes •  Built from GUI components

CSE UOWD

CSCI 213: Java GUI Spring 2013

3

1

All are encapsulated in Java Classes and Packages CSE UOWD CSCI 213: Java GUI Spring 2013 4 Graphical Components button menus title bar menu bar combo box scroll bars CSE UOWD CSCI 213: Java GUI Spring 2013 5 Simple GUI-Based Input/Output with JOptionPane •  Dialog boxes §  Used by applications to interact with the user §  Provided by Java’s JOptionPane class •  Contains input dialogs and message dialogs CSE UOWD CSCI 213: Java GUI Spring 2013 6 2 . colors. fonts. etc.Elements of GUI Programming •  Components §  Visual objects that appear on the screen •  Layouts §  Control over the positioning of components within a container •  Events §  Responses to user actions •  Graphics §  Lines. shapes.

"The sum is " + sum. int sum = number1 + number2. showInputDialog returns to the program the typed by the user as a String. A dialog warning the user of a potential problem. JOptionPane.JOptionPane. A dialog with an informational message to the user.parseInt( firstNumber ). no icon A dialog that contains a message. but no icon.showMessageDialog( null. String secondNumber = JOptionPane. the message dialog is dismissed (removed from the screen) CSCI 213: Java GUI Spring 2013 OK CSE UOWD 8 JOptionPane static constants Message dialog type ERROR_MESSAGE INFORMATION_MESSAGE WARNING_MESSAGE QUESTION_MESSAGE Icon Description A dialog that indicates an error to the user. The program must convert the String to an int Example (2) Text field in which the user types a value OK 100 Input dialog displayed by lines 12 –13 title bar Message dialog displayed by lines 22 –23 When the user clicks . such as clicking a Yes or a No button. "Sum of Two Integers".parseInt( secondNumber ).showInputDialog( "Enter first integer" ). dialog to receive second integer // convert String inputs to int values for use in a calculation ! int number1 = Integer. ! import javax. CSE UOWD CSCI 213: Java GUI Spring 2013 9 3 . int number2 = Integer. This dialog normally requires a response. PLAIN_MESSAGE A dialog that poses a question to the user. // program uses JOptionPane ! ! public class Addition { public static void main( String args[] ) { Show input dialog to receive first integer ! // obtain user input from JOptionPane input dialogs String firstNumber = Show input JOptionPane.PLAIN_MESSAGE ). // add numbersShow ! message dialog to output sum to user ! // display result in a JOptionPane message dialog JOptionPane.swing. } // end method main ! 25 } // end class Addition ! CSE UOWD CSCI 213: Java GUI Spring 2013 7 Input dialog displayed by lines 10–11 Prompt to the user When the user clicks .Example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ! 15 16 17 18 ! 19 20 ! 21 22 23 24 // Example ! // Addition program that uses JOptionPane for input and output.showInputDialog( "Enter second integer" ).

Provides a drop-down list of items from which the user can make a selection by clicking an item or possibly by typing into the box. AWT •  So why do the GUI component classes have a prefix J? §  §  Q: instead of JButton. AWT is prone to platform-specific bugs §  its peer-based approach relies heavily on the underlying platform. and AWT components are referred to as heavyweight components. CSE UOWD Combo Box CSCI 213: Java GUI Spring 2013 11 Swing vs. Provides a list of items from which the user can make a selection by clicking on any item in the list. and flexible library known as Swing components •  Swing components are less dependent on the target platform and use less of the native GUI resource. For this reason. Multiple elements can be selected. versatile.Most Used Components Component JLabel JTextField JButton JCheckBox JComboBox JList JPanel Description Displays uneditable text or icons. Provides an area in which components can be placed and organized. Specifies an option that can be selected or not selected. and blue JComboBox jcboColor = new JComboBox(new String[]{"Red". why not name it simply Button? A: there is a class already named Button in the java. Triggers an event when clicked with the mouse. green. CSE UOWD CSCI 213: Java GUI Spring 2013 12 4 . Can also be used as a drawing area for graphics.awt package •  When Java was introduced. // Create a label with text "Enter your name: " JLabel jlblName = new JLabel("Enter your name: "). // Create a check box with text bold JCheckBox jchkBold = new JCheckBox("Bold"). "Green". CSE UOWD CSCI 213: Java GUI Spring 2013 10 Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"). but not for developing comprehensive GUI projects •  Besides. "Blue"}). •  For every platform on which Java runs. Label Text field Check Box Radio Button Button // Create a text field with text "Type Name Here" JTextField jtfName = new JTextField("Type Name Here"). the AWT components are automatically mapped to the platform-specific components through their respective agents. the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). the AWT user-interface components were replaced by a more robust. // Create a combo box with choices red. Swing components that don’t rely on native GUI are referred to as lightweight components. Can also be used to display editable or uneditable text. Enables user to enter data from the keyboard. •  With the release of Java 2. // Create a radio button with text red JRadioButton jrbRed = new JRadioButton("Red"). known as peers •  AWT is fine for developing simple graphical user interfaces.

GUI Class Hierarchy (Swing) CSE UOWD CSCI 213: Java GUI Spring 2013 13 Container Classes CSE UOWD CSCI 213: Java GUI Spring 2013 14 GUI Helper Classes The helper classes are not subclasses of Component. fonts. CSE UOWD CSCI 213: Java GUI Spring 2013 15 5 . and dimension. They are used to describe the properties of GUI components such as colors.

Swing GUI Components CSE UOWD CSCI 213: Java GUI Spring 2013 16 Components Covered in the Brief Version CSE UOWD CSCI 213: Java GUI Spring 2013 17 Components Covered in the Comprehensive Version CSE UOWD CSCI 213: Java GUI Spring 2013 18 6 .

etc. •  The JFrame class can be used to create windows. •  A simplistic way to look at containment is this: §  A JFrame contains: •  A menu bar •  A content pane CSE UOWD CSCI 213: Java GUI Spring 2013 21 7 . Frame is the basis to contain other user interface components in Java GUI applications. CSE UOWD CSCI 213: Java GUI Spring 2013 20 Frames with Components •  A Frame is a container. Therefore it can contain other components (like buttons. text fields.AWT (Optional) CSE UOWD CSCI 213: Java GUI Spring 2013 19 Frames •  Frame is a window that is not contained inside another window. •  The content pane is the grey area in the Frame window. •  For Swing GUI programs. use JFrame class to create widows.) •  Components are added to the content pane of a frame.

frame.setVisible(true).*. } }! CSE UOWD CSCI 213: Java GUI Spring 2013 23 Adding Components into a Frame! Title bar // Add a button into the frame frame. frame. frame. Content pane CSE UOWD CSCI 213: Java GUI Spring 2013 24 8 .A Picture of Frame Containment CSE UOWD CSCI 213: Java GUI Spring 2013 22 Creating Frames import javax.getContentPane().setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE).swing. 300).add( new JButton("OK")). public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame").setSize(400.

setDefaultCloseOperation( JFrame.setSize(400.Content Pane Delegation in JDK 1. Specifies the size of the frame. Content pane // Add a button into the frame frame. height: int): void +setLocation(x: int.JFrame +JFrame() +JFrame(title: String) +setSize(width: int. frame. CSE UOWD CSCI 213: Java GUI Spring 2013 25 Adding a JButton to a Frame import javax.add(okBtn).EXIT_ON_CLOSE).add( new JButton("OK")).swing. the frame is centered on the screen. Creates a frame with the specified title. CSE UOWD } }! CSCI 213: Java GUI Spring 2013 26 JFrame Class javax.add( new JButton("OK")). CSE UOWD CSCI 213: Java GUI Spring 2013 27 9 . Sets the location of the frame relative to the specified component.setVisible(true). frame. frame. y: int): void +setVisible(visible: boolean): void +setDefaultCloseOperation(mode: int): void +setLocationRelativeTo(c: Component): void +pack(): void Creates a default frame with no title.getContentPane(). Specifies the operation when the frame is closed. 300). public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame").swing. Automatically sets the frame size to hold the components in the frame.*. frame. JButton okBtn = new Jbutton(”Ok”)). If the component is null. Specifies the upper-left corner location of the frame. Sets true to display the frame.5! Title bar // Add a button into the frame frame.

or right •  Typical syntax: in your Frame class’s constructor §  setLayout(new FlowLayout(FlowLayout. but not for frames •  Options: §  left. •  Advantage: resizing the container (frame) will not occlude or distort the view of the components. •  Layout managers are set in containers using the setLayout(LayoutManager) method in a container.LEFT. •  Default for applets and panels.hgap.vgap)) CSE UOWD CSCI 213: Java GUI Spring 2013 30 10 .LEFT)) OR §  setLayout(new FlowLayout(FlowLayout. •  The UI components are placed in containers. CSE UOWD CSCI 213: Java GUI Spring 2013 28 Kinds of Layout Managers •  Basic layouts: §  FlowLayout §  GridLayout §  BorderLayout •  Other layout managers: §  Containers §  Layout Managers. and §  Borders CSE UOWD CSCI 213: Java GUI Spring 2013 29 FlowLayout •  Places components sequentially (left-to-right) in the order they were added •  Components will wrap around if the width of the container is not wide enough to hold them all in a row. Each container has a layout manager to arrange the UI components within the container.Layout Managers •  Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. •  Control the placement of components on the container. •  This is an alternative to hardcoding the pixel locations of the components. center (this is the default).

The alignment of this layout manager (default: CENTER). row by row •  Components will be equal in size •  As container is resized. columns)) OR §  setLayout(new GridLayout(rows. The horizontal gap of this layout manager (default: 5 pixels). and remain in same grid arrangement CSE UOWD CSCI 213: Java GUI Spring 2013 33 11 . hgap: int. and vertical gap. The vertical gap of this layout manager (default: 5 pixels).vgap)) •  Components will be added in order. Creates a FlowLayout manager with a specified alignment.hgap. but omitted in the UML diagram for brevity.Resizing the frame causes the components to wrap around when necessary. components will resize accordingly. CSE UOWD CSCI 213: Java GUI Spring 2013 32 GridLayout •  Arranges components into rows and columns •  In Frame’s constructor: §  setLayout (new GridLayout(rows. vgap: int) The get and set methods for these data fields are provided in the class. Creates a FlowLayout manager with a specified alignment. CSE UOWD CSCI 213: Java GUI Spring 2013 31 The FlowLayout Class java. Creates a default FlowLayout manager. left to right.awt.columns.FlowLayout -alignment: int -hgap: int -vgap: int +FlowLayout() +FlowLayout(alignment: int) +FlowLayout(alignment: int. horizontal gap.

but omitted in the UML diagram for brevity.WEST. BorderLayout. The horizontal gap of this layout manager (default: 0). West.EAST. Creates a default GridLayout manager.GridLayout -rows: int -columns: int -hgap: int -vgap: int +GridLayout() The get and set methods for these data fields are provided in the class. and vertical gap. South. Creates a GridLayout manager with a specified number of rows and hgap: int. region) •  do for each area desired: §  BorderLayout.Resizing the frame causes the components to resize and maintain their same grid pattern. one to each region. CSE UOWD CSCI 213: Java GUI Spring 2013 34 The GridLayout Class java. The number of columns in this layout manager (default: 1). East. CSE UOWD CSCI 213: Java GUI Spring 2013 35 BorderLayout •  Arranges components into five areas: North. horizontal gap. CSE UOWD CSCI 213: Java GUI Spring 2013 36 12 . BorderLayout. and Center •  In the constructor: §  setLayout(new BorderLayout()) OR §  setLayout(new BorderLayout(hgap. The number of rows in this layout manager (default: 1).vgap)) §  for each component: •  add (the_component. the components will be resized but remain in the same locations. •  NOTE: only a maximum of five components can be added and seen in this case.SOUTH. The vertical gap of this layout manager (default: 0). columns: int. or BorderLayout. columns: int) Creates a GridLayout with a specified number of rows and columns.awt. +GridLayout(rows: int.NORTH. vgap: int) columns. BorderLayout. +GridLayout(rows: int.CENTER •  Behavior: when the container is resized.

and vertical gap. The horizontal gap of this layout manager (default: 0). you can use these methods with JPanels: §  add() – to add components to the panel §  setLayout() – to associate a layout manager for the panel CSE UOWD CSCI 213: Java GUI Spring 2013 39 13 .awt. The vertical gap of this layout manager (default: 0). •  Therefore. •  As containers. but omitted in the UML diagram for brevity. vgap: int) Creates a BorderLayout manager with a specified number of horizontal gap. like JFrames. you can combine layouts within the same frame by adding panels to the frame and by adding other components to the panels.BorderLayout -hgap: int -vgap: int +BorderLayout() Creates a default BorderLayout manager. CSE UOWD CSCI 213: Java GUI Spring 2013 38 Using Panels as “Sub-Containers” •  JPanel is a class of special components that can contain other components.Resizing the frame causes the components to resize and maintain their same regions. java. •  This way. NOTE: the CENTER region dominates the sizing. CSE UOWD CSCI 213: Java GUI Spring 2013 37 The BorderLayout Class The get and set methods for these data fields are provided in the class. JPanels can have their own layout managers. +BorderLayout(hgap: int.

g. green. white. green. yellow) are defined as constants in java. This is known as the RGB model. green. and blue components. 255). Since JDK 1. and YELLOW.Testing Panels •  This example uses panels to organize components. GRAY. but they are named as variables with lowercase for the first word and uppercase for the first letters of subsequent words. red. CYAN. Colors are made of red. PINK. The program creates a user interface for a Microwave oven. magenta. pink. ranging from 0 (darkest shade) to 255 (lightest shade). The standard color names are constants. BLUE. r. ORANGE. lightGray. RED. LIGHT_GRAY. blue. frame A textfield p2 A button 12 buttons p1 CSE UOWD CSCI 213: Java GUI Spring 2013 40 The Color Class You can set colors for GUI components by using the java. darkGray.Color class. and blue components. DARK_GRAY. b). GREEN. MAGENTA. CSE UOWD CSCI 213: Java GUI Spring 2013 45 Standard Colors Thirteen standard colors (black.Color. 100. ! Example: Color c = new Color(228. and b specify a color by its red. WHITE. gray.4. Color c = new Color(r.awt. cyan. CSE UOWD CSCI 213: Java GUI Spring 2013 46 14 . g. you can also use the new constants: BLACK.awt. Thus the color names violate the Java naming convention. each of which is represented by a byte value that describes its intensity. orange.

length. for (int i = 0.getAvailableFontFamilyNames(). and Font.BOLD + Font. CSE UOWD CSCI 213: Java GUI Spring 2013 47 The Font Class Font Names Standard font names that are supported in all platforms are: SansSerif. String[] fontnames = e.ITALIC (3) Font myFont = new Font(name.ITALIC. style. size). or DialogInput.PLAIN (0). i++) System. jbtOK. CSE UOWD CSCI 213: Java GUI Spring 2013 48 Finding All Available Font Names GraphicsEnvironment e = GraphicsEnvironment.out.BOLD+Font. Font.ITALIC (2).println(fontnames[i]). 16).setForeground(Color.getLocalGraphicsEnvironment(). Dialog. Font.yellow). CSE UOWD CSCI 213: Java GUI Spring 2013 49 15 .BOLD. i < fontnames. JButton jbtOK = new JButton("OK“). Font myFont = new Font("Serif". Font.BOLD (1). Serif.red). Monospaced.setFont(myFont).Setting Colors You can use the following methods to set the component’s background and foreground colors: setBackground(Color c) setForeground(Color c) Example: jbt. jbt. Font Style Font. Example: Font myFont = new Font("SansSerif ". 12). Font.setBackground(Color.

JPanel p = new JPanel(). •  It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel. CSE UOWD CSCI 213: Java GUI Spring 2013 51 Testing Panels Example This example uses panels to organize components. For example. CSE UOWD CSCI 213: Java GUI Spring 2013 50 Creating a JPanel •  You can use new JPanel() to create a panel with a default FlowLayout manager or new JPanel(LayoutManager) to create a panel with the specified layout manager •  Use the add(Component) method to add a component to the panel. The program creates a user interface for a Microwave oven. p.Using Panels as Sub-Containers •  Panels act as sub-containers for grouping user interface components.add(new JButton("OK")). you actually add it to the content pane of JFrame. To add a component to a panel. ! CSE UOWD CSCI 213: Java GUI Spring 2013 52 16 . •  To add a component to JFrame. you add it directly to the panel using the add method.

awt.Component -font: java. The foreground color of this component.border.gif").Font -background: java. The tool tip text for this component. Returns the height of this component. Removes the component from the container. Returns the width of this component. The font of this component.swing.awt. +remove(comp: Component): void +getLayout(): LayoutManager +setLayout(l: LayoutManager): void +paintComponents(g: Graphics): void Returns the layout manager for this container. Images are normally stored in image files. An icon is a fixed-size picture. getX() and getY() return the coordinate of the component’s upper-left corner within its parent component. CSE UOWD CSCI 213: Java GUI Spring 2013 56 17 . The get and set methods for these data fields are provided in the class.ImageIcon class to represent an icon. but omitted in the UML diagram for brevity.Common Features of Swing Components java.Color -foreground: java. index: int): Component Adds a component to the container with the specified index. The border for this component. but omitted in the UML diagram for brevity.swing.awt. the following statement creates an icon from an image file abc.Container +add(comp: Component): Component Adds a component to the container. Tool tip text is displayed when the mouse points on the component without clicking. You can use new ImageIcon(filename) to construct an image icon.awt. Sets the layout manager for this container.awt.JComponent -toolTipText: String -border: javax. The preferred size of this component. The background color of this component.gif in the image directory under the current class path: ImageIcon icon = new ImageIcon("image/abc. +add(comp: Component.swing. java.Border CSE UOWD 53 Image Icons Java uses the javax. typically it is small and used to decorate components.Color -preferredSize: Dimension -visible: boolean +getWidth(): int +getHeight(): int +getX(): int +getY(): int The get and set methods for these data fields are provided in the class. CSCI 213: Java GUI Spring 2013 javax. For example. Paints each of the components in this container. Indicates whether this component is visible.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer: Get 4 months of Scribd and The New York Times for just $1.87 per week!

Master Your Semester with a Special Offer from Scribd & The New York Times