0% found this document useful (0 votes)
3 views

Lecture9-1

The document outlines Lecture 9-1 of ICS 45J, focusing on programming in Java with an emphasis on graphical user interfaces (GUIs). It covers topics such as event handling, layout management, processing text input, and the use of various GUI components like buttons, check boxes, and menus. Important announcements regarding lab work and course evaluations are also included.

Uploaded by

kamishwang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Lecture9-1

The document outlines Lecture 9-1 of ICS 45J, focusing on programming in Java with an emphasis on graphical user interfaces (GUIs). It covers topics such as event handling, layout management, processing text input, and the use of various GUI components like buttons, check boxes, and menus. Important announcements regarding lab work and course evaluations are also included.

Uploaded by

kamishwang
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

ICS 45J: Programming in Java

Lecture 9-1
GUIs

Emily Navarro
Announcements

• No lecture this Thursday 3/6


• Use the time to work on Lab 9
• Lab 9 is the most time-consuming (and rewarding) lab of the quarter)
• Lab 9 is the last lab on which late passes are accepted
• Complete the ICS final eval for this course to earn 0.5% extra credit
• In your email
• Complete by 3/17 7:50am
• Thursday 3/13 lecture will be pre-recorded and posted
PART 1
Canvas Participation Quiz

Lecture 9-1: Lecture 8-1


Review

Text questions to (562) 684-8307


Last Time

• A generic Java class has one or more type parameters


• Type parameters make generic code safer and easier to read
• Type variables of a generic class follow the class name and are
enclosed in angle brackets
• Use type parameters for the types of generic instance variables,
method parameter variables, and return values
• A generic method is a method with a type parameter
• Type parameters can be constrained with bounds
• The virtual machine erases type parameters, replacing them with their
bounds or Objects

Text questions to (562) 684-8307


PART 2
Learning Objectives

• To implement event listeners in graphical applications


• To use layout managers to arrange user interface
components in a container
• To use text components to capture and display text in a
graphical application
• To become familiar with common user interface
components, such as radio buttons, check boxes, and menus

Text questions to (562) 684-8307


Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


Frame Windows

• A graphical application shows information inside a frame


• To show a frame:
1. Construct an object of the JFrame class:
JFrame frame = new JFrame();

2. Set the size of the frame:


frame.setSize(300, 400);

3. If you’d like, set the title of the frame:


frame.setTitle("An empty Frame");

4. Set the “default close operation:”


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

5. Make the frame visible:


frame.setVisible(true);

Text questions to (562) 684-8307


Demo: EmptyFrameViewer.java

Text questions to (562) 684-8307


PART 3
Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


Event Handling
• In an event-driven user interface, the program receives an event whenever the user manipulates an
input component
• User interface events include key presses, mouse moves, button clicks, etc.
• Since most programs don’t want to be flooded by irrelevant events, a program must indicate which
events it needs to receive
• Event listeners:
• A program indicates which events it needs to receive by installing event listener objects
• Belongs to a class provided by the application programmer
• Its methods describe the actions to be taken when an event occurs
• Notified when event happens
• Event source:
• User interface component that generates a particular event
• Add an event listener object to the appropriate event source
• When an event occurs, the event source notifies all event listeners

Text questions to (562) 684-8307


Event Handling Example

• A program prints a message whenever a button is clicked


• Button listeners must belong to a class that implements the
ActionListener interface:
public interface ActionListener {
void actionPerformed(ActionEvent event);
}

• Supply a class whose actionPerformed method contains the


instructions that you want executed whenever the button is clicked
public class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
System.out.println("I was clicked.");
}
}

Text questions to (562) 684-8307


Event Handling – Listening for Events

• event parameter of actionPerformed contains details about the event, such as


the time at which it occurred
• Construct an object of the listener and add it to the button:
ActionListener listener = new ClickListener();
button.addActionListener(listener);

• Whenever the button is clicked, it calls:


listener.actionPerformed(event);

And the message is printed


• Use a JButton component for the button; attach an ActionListener to the
button

Text questions to (562) 684-8307


Demo: ButtonViewer.java and
ClickListener.java

Text questions to (562) 684-8307


Using Inner Classes for Listeners (I)

• Implement simple listener classes as inner classes like this:


JButton button = new JButton(". . .");

// This inner class is declared in the same method as the


button variable
class MyListener implements ActionListener {
. . .
}

ActionListener listener = new MyListener();


button.addActionListener(listener);
• Advantages:
• Places the trivial listener class exactly where it is needed, without cluttering up the
remainder of the project
• Methods of an inner class can access instance variables and methods of the surrounding
class

Text questions to (562) 684-8307


Demo: InvestmentViewer1.java

Text questions to (562) 684-8307


PART 4
Expanding InvestmentViewer with JLabel
and JPanel

• We need a user interface component that displays a message:


JLabel label = new JLabel("balance: " + account.getBalance());

• Use a JPanel container to group multiple user interface components together:


JPanel panel = new JPanel();
panel.add(button);
panel.add(label);
frame.add(panel);

Text questions to (562) 684-8307


Demo: InvestmentViewer2.java

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 9-1: Frame


Windows and Event
Handling

Text questions to (562) 684-8307


PART 5
Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


Layout Management

• In Java, you build user interfaces by adding components into containers


• Use a layout manager to place the components
• JPanel uses Flow layout by default

Text questions to (562) 684-8307


Border Layout

• Components are placed toward areas of a container NORTH, EAST, SOUTH, WEST, or
CENTER
• Specify one when adding components:
panel.setLayout(new BorderLayout());

panel.add(component, BorderLayout.NORTH);
• Components expand to fill space

Text questions to (562) 684-8307


Grid Layout

• Components are placed in boxes in a simple table arrangement


• Specify the size (rows then columns) of the grid
• Then add components which will be placed from the upper left, across, then down
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
buttonPanel.add(button7);
buttonPanel.add(button8);
buttonPanel.add(button9);
buttonPanel.add(button4);
. . .

Text questions to (562) 684-8307


Achieving Complex Layouts

• Create complex layouts by nesting panels


• Give each panel an appropriate layout manager
• Panels have invisible borders, so you can use as many panels as you
need to organize components
JPanel keypadPanel = new JPanel(); 0
keypadPanel.setLayout(new BorderLayout());
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(4, 3));
buttonPanel.add(button7);
buttonPanel.add(button8);
// . . .
keypadPanel.add(buttonPanel, BorderLayout.CENTER);
JLabel display = new JLabel("0");
keypadPanel.add(display, BorderLayout.NORTH);

Text questions to (562) 684-8307


Using Inheritance for Complex Frames

• Use inheritance for complex frames


• Design a subclass of JFrame:
• Store components as instance variables
• Initialize them in the constructor of your subclass
• Easy to add helper methods to organize code
• Demo: FilledFrame.java

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 9-1: Layout


Management

Text questions to (562) 684-8307


PART 6
Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


Processing Text Input (I)

• The JTextField class provides a text field


• Specify the width for the text field
• If the user exceeds this width, text will “scroll” left
final int FIELD_WIDTH = 10;
final JTextField rateField = new JTextField(FIELD_WIDTH);

Text questions to (562) 684-8307


Processing Text Input (II)

• Add a label to describe the field:


JLabel rateLabel = new JLabel("Interest Rate: ");

• Add a button for user to indicate input is complete


• actionPerformed method can use getText to get input as a String
• Convert to a numeric value if used for calculations
class AddInterestListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
double rate = Double.parseDouble(rateField.getText());
double interest = balance * rate / 100;
balance = balance + interest;
resultLabel.setText("Balance: " + balance);
}
}

Text questions to (562) 684-8307


Demo: InvestmentFrame2.java

Text questions to (562) 684-8307


Text Areas

• Create multi-line text areas with a JTextArea object


• Set the size in rows and columns
final int ROWS = 10; // Lines of text
final int COLUMNS = 30; // Characters in each row
JTextArea textArea = new JTextArea(ROWS, COLUMNS);

• Use the setText or append method to set/append to the text of a text field or
text area
textArea.append(balance + "\n");

• Can use the text area for display purposes only


textArea.setEditable(false);

Text questions to (562) 684-8307


TextComponent Class

• JTextField and JTextArea are subclasses of JTextComponent


• setText and setEditable are declared in the JTextComponent class
• append method is only declared in JTextArea

Text questions to (562) 684-8307


Scrolling

• To add scroll bars, use JScrollPane:


JScrollPane scrollPane = new JScrollPane(textArea);

Text questions to (562) 684-8307


Demo: InvestmentFrame3.java

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 9-1: Processing


Text Input

Text questions to (562) 684-8307


PART 7
Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


GUI Components for Selections

• Radio Buttons for a small set of mutually exclusive choices


• Check Boxes for a binary choice
• Combo Boxes for a large set of choices

Text questions to (562) 684-8307


Radio Buttons

• Only one button in a set can be selected


• Selecting a button clears previous selection
• Create each button individually
• Add all buttons in the set to a ButtonGroup object:
JRadioButton smallButton = new JRadioButton("Small");
JRadioButton mediumButton = new JRadioButton("Medium");
JRadioButton largeButton = new JRadioButton("Large");
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);
group.add(largeButton);

• Use isSelected to find out whether a button is selected:


if (largeButton.isSelected()) { size = LARGE_SIZE; }

Text questions to (562) 684-8307


Radio Button Panels

• Use a panel for each set of radio buttons


• The default border for a panel is invisible (no border)
• You can add a border to a panel to make it visible
• You can also add a title
JPanel panel = new JPanel();
panel.add(smallButton);
panel.add(mediumButton);
panel.add(largeButton);
panel.setBorder(new TitledBorder(new EtchedBorder(),"Size"));

Text questions to (562) 684-8307


Check Boxes

• A check box has two states: checked and unchecked


• Use for choices that are not mutually exclusive
• Because check box settings do not exclude each other, you do not need to place a
set of check boxes inside a button group
• Construct a check box:
JCheckBox italicCheckBox = new JCheckBox("Italic");

• Use isSelected to find out whether a check box is selected

Text questions to (562) 684-8307


Combo Boxes

• A combo box is a combination of a list and a text field


• Clicking the arrow to the right of the text field opens the list of selctions
• Use a combo box for a large set of choices
• Use when radio buttons would take up too much space
• A combo box can be either:
• Closed (shows one selection)
• Open (shows multiple selections)
• It can also be editable
• Type a selection into a blank line
facenameCombo.setEditable();

Text questions to (562) 684-8307


Adding and Selecting Items

• Add text “items” to a combo box that will show in the list:
JComboBox facenameCombo = new JComboBox();
facenameCombo.addItem("Serif");
facenameCombo.addItem("SansSerif");
. . .

• Use the getSelectedItem method to return the selected item (as an Object)
• Combo boxes can store other objects in addition to strings, so casting to a String
may be required:
String selectedString = (String) facenameCombo.getSelectedItem();

Text questions to (562) 684-8307


Handling Input Events

• Radio buttons, check boxes, and combo boxes generate an


ActionEvent when selected
• In FontViewer program, listener gets all events
• Simply check the state of each component using isSelected and
getSelectedItem methods
• Then redraw the label with the new font

Text questions to (562) 684-8307


FontFrame Layout

Text questions to (562) 684-8307


Demo: FontFrame.java

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 9-1: Choices

Text questions to (562) 684-8307


PART 8
Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


Menus (I)

• A frame can contain a menu bar


• A menu bar contains menus
• A menu contains submenus and menu items
• Menu items can be added to each menu or submenu
• First, add the menu bar to the frame:
public class MyFrame extends Jframe {
public MyFrame() {
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
. . .
}
. . .
}

Text questions to (562) 684-8307


Menus (II)

• Add menus to the menu bar:


JMenu fileMenu = new JMenu("File");
JMenu fontMenu = new JMenu("Font");
menuBar.add(fileMenu);
menuBar.add(fontMenu);

• Add menu items and subitems:


JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(exitItem);
JMenu styleMenu = new JMenu("Style");
fontMenu.add(styleMenu); // A submenu

• Add a listener to each menu item:

ActionListener listener = new ExitItemListener();


exitItem.addActionListener(listener);

Text questions to (562) 684-8307


Creating Menus

• Use a separate method for each menu or set of related menus:


public JMenu createFaceMenu() {
JMenu menu = new JMenu("Face");
menu.add(createFaceItem("Serif"));
menu.add(createFaceItem("SansSerif"));
menu.add(createFaceItem("Monospaced"));
return menu;
}

Text questions to (562) 684-8307


Adding Listeners to Menu Items (I)

• createFaceItem method needs to set the font face:


• Set the current face name
• Make the new font from the current face, size, and style, and apply it to label
• Create a FaceItemListener class to listen for face item name actions:
class FaceItemListener implements ActionListener {
private String name;
public FaceItemListener(String newName) { name = newName; }
public void actionPerformed(ActionEvent event) {
faceName = name; // Sets an instance variable of the frame class
setLabelFont();
}
}
• Install a listener object with the appropriate name:
public JMenuItem createFaceItem(String name) {
JMenuItem item = new JMenuItem(name);
ActionListener listener = new FaceItemListener(name);
item.addActionListener(listener);
return item;
}

Text questions to (562) 684-8307


Adding Listeners to Menu Items (II)
• Better to make a local inner class in the createFaceItem method
• actionPerformed method can access the name parameter variable directly (rather than
passing it)
public JMenuItem createFaceItem(final String name) {
// Final variables can be accessed from an inner class method
class FaceItemListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
facename = name; // Accesses the local variable name
setLabelFont();
}
}
JMenuItem item = new JMenuItem(name);
ActionListener listener = new FaceItemListener(name);
item.addActionListener(listener);
return item;
}

• Same strategy used for the createSizeItem and createStyleItem methods

Text questions to (562) 684-8307


Demo: FontFrame2 and FontViewer2

Text questions to (562) 684-8307


Canvas Participation Quiz

Lecture 9-1: Menus

Text questions to (562) 684-8307


Agenda

• Frame Windows
• Event Handling
• Layout Management
• Processing Text Input
• Choices
• Menus
• GUI Builders

Text questions to (562) 684-8307


GUI Builders

• Drag and drop components


onto a panel
• Customize fonts, colors, text,
and so on with a dialog box
• Define event handlers by
picking the event to process
and provide the code snippet
for the listener method

Text questions to (562) 684-8307


Summary

• User-interface events include key presses, mouse moves, button clicks, menu
selections, etc.
• An event listener’s (ActionListener) methods describe the actions to be
taken when an event occurs
• UI components are arranged by placing them inside containers
• Each container has a layout manager that directs the arrangement of its
components
• Use a JTextField for reading a single line of input, a JLabel next to each text
field, and a JTextArea to show multiple lines of text
• Use radio buttons for a small set of mutually exclusive choices, a check box for a
binary choice, or a combo box for a large set of choices
• A frame contains a menu bar, which contains menus, which contains submenus and
menu items
Text questions to (562) 684-8307
Announcements

• No lecture this Thursday 3/6


• Use the time to work on Lab 9
• Lab 9 is the most time-consuming (and rewarding) lab of the quarter)
• Lab 9 is the last lab on which late passes are accepted
• Complete the ICS final eval for this course to earn 0.5% extra credit
• In your email
• Complete by 3/17 7:50am
• Thursday 3/13 lecture will be pre-recorded and posted

You might also like