Lecture2 GUI Basics
Lecture2 GUI Basics
Interfaces
Objectives - by the end of this chapter, you
should be able to do the following:
– String manipulation
– write a simple graphical user interface in Java
using Swing;
– find out how to use components by browsing the
Swing Tutorial and the Java API;
– program listeners to respond to user generated
events;
– use layout managers to arrange components
attractively in windows
Strings
index 0 1 2 3 4 5 6 7
char P . D i d d y
boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2,
case-blind
if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);
Methods — replace
– Output: First name: Abebe, Middle name: Kebede, Lat Name: Lema
Review Questions:
• Labels
– Provide text instructions on a GUI
– Read-only text
– Programs rarely change a label's contents
– Class JLabel (subclass of JComponent)
• Methods
– Can declare label text in constructor
– myLabel.setToolTipText( "Text" )
• Displays "Text"in a tool tip when mouse over label
– myLabel.setText( "Text" )
– myLabel.getText()
JTextField and JPasswordField
• Example
– Create JTextFields and a JPasswordField
– Create and register an event handler
• Displays a dialog box when Enter pressed
JButton
• Button
– Component user clicks to trigger an action
– Several types of buttons
• Command buttons, toggle buttons, check boxes, radio buttons
• Command button
– Generates ActionEvent when clicked
– Created with class JButton
• Inherits from class AbstractButton
• Jbutton
– Text on face called button label
– Each button should have a different label
– Support display of Icons
Example Summary
JFrame
…
content pane
JLabel
A first Swing application
• Examples:
– When the user presses a button we want to save a file
– When the user closes the program we want to ask “are you
sure?”
– ...
• First example
• Improved example
TextField Event example
Panels
JFrame getContentPane()
JFrame
Panels
JPanel
background.add()
Panels
B
JTextArea
Atomic components
B
B
JTextArea
B
Arranging components