Graphical user interfaces (GUIs) present information to users visually using components like buttons, text fields, labels etc. Java provides the Abstract Window Toolkit (AWT) and Swing toolkit for building GUIs. Some key GUI components in Java include JButton for buttons, JTextField for text fields, JLabel for labels, JRadioButton for radio buttons, JCheckBox for checkboxes, JComboBox for drop-down lists, JTextArea for multi-line text, and JFrame for windows. JFrame methods like add(), setVisible(), setLocation(), setSize() are used to control frames. Dialog boxes are also used for input/output using the JOptionPane class.
Report
Share
Report
Share
1 of 45
More Related Content
Chap 1 - Introduction GUI.pptx
2. GUI
• A graphical user interface (GUI) presents a user-friendly
mechanism for interacting with an application.
• A GUI gives an application a distinctive “look” and “feel.”
• Providing different applications with consistent, intuitive
user interface components allows users to be somewhat
familiar with an application.
• so that they can learn it more quickly and use it more
productively.
3. Elements of GUI Programming
• Components
–Visual objects that appear on the screen – label, button,
image…
• Layouts
–Control over the positioning of components within a
container
• Events
–Responses to user actions
• Graphics
–Lines, shapes, colors, fonts, etc.
• All are encapsulated in Java Classes and Packages
4. Components of GUI
Two categories of Java GUI Component classes:
AWT – Abstract Windows Toolkit (java.awt package)
• The older version of the components
• Rely on “peer architecture”…drawing done by the OS
platform on which the application/applet is running
• Considered to be “heavy-weight”
Swing (javax.swing package)
• Newer version of the components
• No “peer architecture”…components draw themselves
• Most are consdered to be “lightweight”
7. Creating GUI Objects
// Create a button with text OK
JButton jbtOK = new JButton("OK");
// Create a label with text "Enter your name: "
JLabel jlblName = new JLabel("Enter your name: ");
// Create a text field with text "Type Name Here"
JTextField jtfName = new JTextField("Type Name Here");
// Create a check box with text bold
JCheckBox jchkBold = new JCheckBox("Bold");
// Create a radio button with text red
JRadioButton jrbRed = new JRadioButton("Red");
// Create a combo box with choices red, green, and blue
JComboBox jcboColor = new JComboBox(new String[]{"Red",
"Green", "Blue"});
9. 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.
GUI with Example
• As an example of a GUI, the following figure contains an
Internet Explorer web-browser window with some of its GUI
components labeled.
• At the top is a title bar that contains the window’s title. Below
that is a menu bar containing menus (File, Edit, View, etc.).
10. Example of JFrame
import javax.swing.*;
public class MyFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("MyFrame"); // Create a frame
frame.setSize(400, 300); // Set the frame size
frame.setLocationRelativeTo(null); // New since JDK 1.4
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Display the frame
}
}
11. Framework for building GUI Applications
• Most windows you will create are an instance of class JFrame
or a subclass of JFrame.
• JFrame provides the basic attributes and behaviors of a window
—a title bar at the top of the window, and
— buttons to minimize, maximize and close the window.
12. Simple JFrame Example
// Sets several properties of a window frame.
import java.awt.*; // for Dimension
import javax.swing.*; // for GUI components
public class SimpleFrame2 {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setForeground(Color.WHITE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(new Point(10, 50));
f.setSize(new Dimension(300, 120));
f.setTitle("A frame");
f.setVisible(true);
}
} Output :
13. Simple GUI-Based Input/Output with JOptionPane
• Most applications you use on a daily basis use windows or
dialog boxes (also called dialogs) to interact with the user.
• For example, e-mail programs allow you to type and read
messages in a window provided by the e-mail program.
• Typically, dialog boxes are windows in which programs display
important messages to the user or obtain information from the
user.
• Java’s JOptionPane class (package javax.swing) provides
prepackaged dialog boxes for both input and output.
• These dialogs are displayed by invoking static JOptionPane
methods.
14. Example: Input Dialogs
// Addition program that uses JOptionPane for input and output.
import javax.swing.JOptionPane; // program uses JOptionPane
public class Addition{
public static void main( String args[] ) {
// obtain user input from JOptionPane input dialogs
String num1 = JOptionPane.showInputDialog( "Enter first integer" );
String num2 = JOptionPane.showInputDialog( "Enter second integer" );
// convert String inputs to int values for use in a calculation
int number1 = Integer.parseInt(num1);
int number2 = Integer.parseInt( num2);
int sum = number1 + number2; // add numbers
// display result in a JOptionPane message dialog
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum of Two Integers", JOptionPane.PLAIN_MESSAGE );
}
}
16. Simple JFrame Example
// Sets several properties of a window frame.
import java.awt.*; // for Dimension
import javax.swing.*; // for GUI components
public class SimpleFrame2 {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setForeground(Color.WHITE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocation(new Point(10, 50));
f.setSize(new Dimension(300, 120));
f.setTitle("A frame");
f.setVisible(true);
}
}
Output :
18. JButton
• A button is a component the user clicks to trigger a specific
action.
• A Java application can use several types of buttons, including
command buttons, checkboxes, toggle buttons and radio buttons.
• A command button generates an ActionEvent when the user clicks
the button. Command buttons are created with class JButton.
• The text on the face of a JButton is called a button label.
• A GUI can have many JButtons, but each button label typically
should be unique in the portion of the GUI that is currently
displayed.
• E.g
19. Example of Button Declaration
JButton button1 = new JButton("I'm the first button");
JButton button2 = new JButton("The second button");
Output:
20. Text Fields and Password Fields
• Each of these components is a single-line area in which the
user can enter text via the keyboard.
• Applications can also display text in a JTextField.
• A JPasswordField shows that characters are being typed as
the user enters them, but hides the actual characters with
an echo character, assuming that they represent a
password that should remain known only to the user.
21. Cont…(Text Fields and Password Fields)
• When the user types data into a JTextField or a
JPasswordField, then presses Enter, an event occurs.
• They are created with a class JTextField and JPasswordField
respectively.
• Example of JTextField and JPasswordField Declaration
JTextfield tf = new JTextfield(20);
JPasswordField pf = new JPasswordField (20);
• JTextfield =>
• JPasswordField =>
22. Labeling GUI Components (JLabel)
• A Label displays a single line of readonly text, an image, or
both text and an image.
• Applications rarely change a label’s contents after creating it.
• Such text is known as a label and is created with class JLabel—
a subclass of JComponent.
• Example of JLabel
JLabel lb = new JLabel("This is a label");
OUTPUT =>
23. JRadioButton
• Radio buttons (declared with class JRadioButton) are
normally appear as a group in which only one button can be
selected at a time .
• Selecting a different radio button forces all others to be
deselected.
• Radio buttons are used to represent mutually exclusive
options (i.e., multiple options in the group cannot be
selected at the same time).
• Example of creating JRadioButton
JRadioButton m = new JRadioButton(“male”);
JRadioButton f = new JRadioButton(“female”);
OUTPUT =>
24. JCheckBox
• Used to select the desired thing.
• It can be used for multiple selection of from a group of
options.
• Example of creating JCheckBox
JCheckBox am = new JCheckBox(“Amharic”);
JCheckBox en = new JCheckBox(“English”);
JCheckBox m = new JCheckBox(“Other”);
OUTPUT =>
25. JComboBox
• A combo box (sometimes called a drop-down list) provides a list
of items from which the user can make a single selection.
• Combo boxes are implemented with class JComboBox, which
extends class JComponent.
• JComboBoxes generate ItemEvents like JCheckBoxes and
JRadioButtons.
• Example of creating JComboBox
JComboBox colorChoice = new JComboBox();
colorChoice.addItem("Red");
colorChoice.addItem("Blue");
colorChoice.addItem("Green");
colorChoice.addItem("Black");
26. JTextArea
• A JTextArea provides an area for manipulating multiple lines of
text.
• Like class JTextField, JTextArea is a subclass of JTextComponent,
which declares common methods for JTextFields, JTextAreas and
several other text-based GUI components.
• Example of creating JTextArea
JTextArea ta= new JTextArea (50,30);
OUTPUT =>
27. JFrame Methods
• add(Object) - adds objects to the frame.
• setVisible(boolean) - makes the frame visible
• setLocation(int x, int y) – aligns top left corner of frame with
coordinates on screen
• setSize(int width, int height) – sets size of frame in pixels
• setDefaultCloseOperation(Windows.constants.EXIT_ON_CLOS
E);
27
28. JFrame Code
import javax.swing.*;
import java.awt.*;
public class UpperCaseConverter extends JFrame
{
public UpperCaseConverter(String name){
super(name);
setLocation(300, 100);
setSize (400,300);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]){
UpperCaseConverter ucc = new UpperCaseConverter("Convert to Upper Case");
ucc.setVisible(true);
}
}
28
Constructor sets the title,
size and location of the
JFrame
Instantiates JFrame
and makes it visible
30. JPanel
• However, we want to put several buttons in the North
region of the GUI, but BorderLayout only allows one
component per region…
• Add a second level container like a JPanel.
• JPanels have a FlowLayout manager by default.
30
31. FlowLayout
• Lays components in a fluid direction as determined by its
orientation.
• By default, orientation is L -> R, T -> B.
• Possible to set the horizontal and vertical width between
components.
• Components take preferred size.
– For buttons, preferred size is the size of the text within them.
31
32. JPanel and FlowLayout Code
//omitting code here from previous example
public class UpperCaseConverter extends JFrame
{
JButton upper;
JButton clear;
public UpperCaseConverter(String name){
//omitting code here from previous example
JPanel top;
top = new JPanel();
upper = new JButton("UPPER");
clear = new JButton("CLEAR");
top.add(upper);
top.add(clear);
add(top, BorderLayout.NORTH);
}
//omitting code here from previous example
}
32
33. JPanel and FlowLayout Example
• Code on previous page renders as follows:
• But, we also need a text field to enter text.
33
34. Second JPanel
public class UpperCaseConverter extends JFrame
{
//code omitted from previous example
JTextField input;
public UpperCaseConverter(String name){
//code omitted from previous example
JPanel bottom = new JPanel();
JLabel label = new JLabel("Enter text ->");
input = new JTextField(20);
bottom.add(label);
bottom.add(input);
add(bottom, BorderLayout.SOUTH);
}
//code omitted from previous example
}
34
JLabel may also take
an Icon or both a
String and Icon in its
constructor
JTextField takes an int
which indicates the
number of characters
to be displayed
36. JTextArea
• Add JTextArea reference to object data so that it can be
referenced by all member methods.
• Instantiate JTextArea reference in constructor method and add
reference to the center of the JFrame.
JTextArea output;
output = new JTextArea(10, 20);
add(output);
36
Declare outside of methods so object data
Constructor for JTextArea
takes number of rows and
columns
38. JComponent Methods
• There exists several JComponent methods that allow you to
change the look of a component
– setBackground(Color)
– setForeground(Color)
– setFont(Font)
– setPreferredSize(Dimension)
– setAlignmentX(float)
– setAlignmentY(float)
38
Values for all the arguments
of these methods are already
defined in Java.
39. More LayoutManagers
• Seven Basic Layout Managers in Java
–BorderLayout
–BoxLayout
–CardLayout
–FlowLayout
–GridLayout
–GridBagLayout
–OverlayLayout
39
40. GridLayout
• Creates a grid with number of rows and columns given in the
constructor
• One component per cell
• Cells of equal size
• Component take the size of the cell
40
41. GridLayout Code
import java.awt.*;
import javax.swing.*;
public class ButtonGrid extends JFrame {
public ButtonGrid() {
super("Button Grid Example");
setLayout(new GridLayout(3,2));
setSize(300,400);
add(new JButton("1"));
add(new JButton("2"));
add(new JButton("3"));
add(new JButton("4"));
add(new JButton("5"));
add(new JButton("6"));
}
public static void main(String arg[]){
ButtonGrid bg = new ButtonGrid();
bg.setVisible(true);
}
}
41
Compare the order in which
the buttons are added to the
GUI on the next page.
The setLayout method
changes a container’s
LayoutManager.
43. Event Driven Programming
• How do we get a GUI to respond to interactions?
• We now need to handle inputs from the user by programming
interactions into the GUI.
• The programming of interactions to the GUI is called event-
handling or known as event-driven programming.
45. …cont
• In figure 5, we see a few new terms:
event sources,
event handlers and
dispatching mechanism.
• Event Sources creates events whenever it is used (i.e. clicking a button on the
GUI),
• Dispatching mechanism queues incoming events while determining its
event type,
event is sent to the event handler that deals with events of that type (i.e.
events from button “1” to Handler 1, events from button “2” to Handler
2, events from button “3” to Handler 3).
• Event handler can react to an event from an event source; such as having
events from buttons “1” and “2” to be handled by Handler 1.
• In Swing, the equivalent to an event source would be a JButton component,
while event handlers are known as listeners.