Powerpoint Slides - Purdue University

Download Report

Transcript Powerpoint Slides - Purdue University

Java Swing
th
4 April 2008
CS 180
Department of Computer Science,
Purdue University
GUIs
• Windowing systems that interact with
users often are called GUIs.
• A GUI accepts information from a user
and makes it available to the program
for processing.
• Most of the interaction is graphical in
nature.
Controls on GUI
• WINDOW
• FRAME
• MENU
• BUTTON
• TEXT BOX
• COMBO BOX
Many more….
Event Driven Programming
• Most GUI programs involve events and
event handlers.
• A GUI event is an object that represents
some action such as clicking the
mouse, dragging the mouse, pressing a
keyboard key, clicking the close-window
button on a window, etc.
• When an object generates an event, it is
said to fire the event.
Programming Example: A Simple
Window
• This simple program produces a window and displays
some text.
– We will explore the following
• Jframe : to create a window
• JLabel : to create a label
• getContentPane().add() : add a component such as a label to the
content pane of the window
• setTitle() : set the title of the window
• setSize() : set the size of the window
• setVisible() : Method setVisible permits the programmer to specify
when GUI objects should be displayed and when they should not
import javax.swing.*;
import java.awt.*;
Example
public class makeWindow {
A Frame
public static void main(String args[])
{
int width=300;
int height=200;
JFrame myWindow=new JFrame();
//create the window
myWindow.setSize(width,height);
//set the title of the window
myWindow.setTitle("this is a window");
//create the label
JLabel myLabel=new JLabel("this is a label");
//add the label to the content pane of the window
myWindow.getContentPane().add(myLabel);
//set color of the content pane
myWindow.getContentPane().setBackground(Color.CYAN);
//make the window visible
myWindow.setVisible(true);
}
}
This colored area is
the content pane
Exploring JFrame : Some methods
•A window class normally is derived from class JFrame.
•A derived window class inherits all the methods from class JFrame.
Window Listeners
• A window listener listens to events from a
window, such as a click on the closewindow button.
• A window listener is registered when it
becomes associated with the object(s) to
which it listens.
Clicking the Close-Window Button
An Example
• Component : Window
• Event: Window Closing
• Listener: performs the following tasks
– Display a dialog box – telling the user that you are
exiting the system
– Exit the window
• Note: If the window-close button is not
programmed, a click causes the window to
disappear, but does not cause the program to
end.
Example Code
import javax.swing.*;
import java.awt.*;
public class makeWindow {
public static void main(String args[])
{
int width=300;
int height=200;
JFrame myWindow=new JFrame();
………
…………..
//same code as explained in slide 6
……………………
Listener Class
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JPopupMenu;
import javax. swing.*;
public class makeWindowListner extends
WindowAdapter{
public void windowClosing(WindowEvent e)
{
// Modal dialog with OK button
String message = "You are exiting this window";
JOptionPane.showMessageDialog(null, message);
//set listener
makeWindowListner myListener=
new makeWindowListner();
myWindow.addWindowListener(myListener);
}
•
}
System.exit(0);
}
}
Example: Output
Step 1: user clicks this
close button
Step 2: user will see this
dialog box
Step 3: window is
closed
Methods of Class WindowAdapter
Some examples:
Methods of Class
WindowAdapter, cont.
• When you define a derived class of
abstract class WindowAdapter, you override
and redefine only those methods that you
need.
• Because class WindowAdapter is abstract,
this class can be used only as a base
class for defining other classes.
What to Import
• It may be simpler to use
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
rather than trying to determine which
import statements are needed for a
particular window interface.
– event.* represents a package within
java.awt.
Frame-Content Pane Layout
• A frame is a component container that displays
its contents in a top-level window with a title bar
and buttons to resize, iconify, maximize, and
close the frame.
• Unlike most Swing containers, adding a
component to a frame is not done with the
JFrame.add() method. This is because the frame
holds several panes and it is necessary to
specify a particular pane to which to add the
component.
• The pane that holds child components is called
the content pane.
• By default the content pane has a border
layout
Border Layout, cont.
• A BorderLayout manager can place a component into
any of five regions.
• Regions which are unused give up their space to
BorderLayout.CENTER.
• This layout limits the GUI to five objects, these are
almost always five (or fewer) JPanels.
•
equivalent forms:
content.add(label3, BorderLayout.CENTER);
and
content.add(label3, “Center”);
and (for center ONLY)
content.add(label3);
Some Layout Managers
Buttons
• A button is a GUI component that looks
like a button and does something when it
is clicked using a mouse.
• Like a label, a button is created and added
to a container.
• Unlike a label, a button can fire an event
and the event can cause a GUI to perform
some action.
Adding Buttons
• A button is created using
JButton Button_Name = new
JButton(“Button_Label”);
• A button is added to a container using
Container_Name.add(Button_Name);
Adding Buttons, cont.
Adding Buttons, cont.
Close-Window Buttons and
JButtons
• A button added to a GUI is an object of
class JButton.
• A close-window button is not an object of
class JButton. Instead, it is part of a JFrame
object.
Action Listeners and Action Events
• For each button, the GUI needs to
– register (specify) the listener object(s).
– define the methods to be invoked when an
event is fired.
• For a statement such as
stopButton.addActionListener(this);
the class ButtonDemo is itself the listener class.
• Buttons fire action events which are handled by
action listeners.
• An action listener is an object of type
ActionListener, and ActionListener is an interface
Action Listeners and Action Events,
cont.
• To make a class into an ActionListener
– add implements ActionListener to the heading of
the class definition
– define a method named ActionPerformed.
– register the ActionListener object with the
component that will fire the event using the
method addActionListener
– (A component may register with more than
one listener.)
Buttons and an Action Listener
The actionPerformed Method
• An actionListener class must have a
method named actionPerformed that has
one parameter of type ActionEvent.
• syntax
public void actionPerformed(ActionEvent
e)
{
Code_for_Actions_Performed
}
Code a GUIs Appearance and
Actions Separately
• Code for a Swing GUI is simpler if it is
divided into two parts:
– the GUI’s appearance on the screen
– the GUI’s actions.
• In a complicated Swing GUI, either of
these tasks by itself can be formidable.
The Model-View-Controller Pattern
What is MVC?
• Model-view-controller (MVC) is an architectural pattern.
• Pattern isolates business logic from user interface.
• Results in an application where it is easier to modify
either the visual appearance or the underlying business
rules without affecting the other.
• Model represents the information (the data) of the
application and the business rules used to manipulate
the data
• View corresponds to elements of the user interface such
as text, checkbox items, and so forth
• Controller manages details involving the communication
to the model of user actions such as keystrokes and
mouse movements.
Method setActionCommand
• Every object that fires an action event has an
associated string known as the action
command for that component.
• e.getActionCommand() returns the action
command for the component that fired e.
• The default action command for a button is
the string written on it.
• Method setActionCommand can be used to
change the action command for the object.
Method setActionCommand,
cont.
• example
JButton stopButton = new JButton(“Red”);
stopButton.setActionCommand(“Stop”);
• This permits the same string to be written
on two different buttons, but with the two
buttons distinguished from one another by
the program.
Container Classes
• The JPanel Class
• The Container Class
• Class JPanel
• java.lang.Object
– java.awt.Component
•
java.awt.Container
– javax.swing.JComponent
» javax.swing.JPanel
Building GUI Classes
• New classes for a GUI often are built using
existing classes.
• Two principal (and compatible) approaches:
– use inheritance (for example, using a JFrame to
make a derived class)
– use a Swing class as a container, placing
components in the container (for example,
adding a button to a content pane)
The JPanel Class
• A GUI can be organized hierarchically, with window-like
containers inside other window-like containers.
• Class JPanel is a simple container that does little more
than hold components.
• Components can be placed in a JPanel which can be
placed in another JPanel, … which can be placed in a
JFrame.
• To place two components in BorderLayout.SOUTH for
example, simply place the two components in a panel
and place the panel in the BorderLayout.SOUTH position.
• The panel has its own layout manager.
The JPanel Class, cont.
The JPanel Class, cont.
The Container Class
• Class Container is a predefined class.
• An object of a class which descends from class
Container is called a container class and can
have components added to it.
• Class JFrame is a descendent of class Container,
permitting any JFrame object to hold labels,
buttons, panels, and other components.
• Class JPanel is a descendent of class Container,
permitting any JPanel object to hold labels,
buttons, other panels, and other components.
The JComponent Class
• Class JComponent is similar to class Container, and
plays a similar role for components.
• Any class that descends from JComponent is called
a JComponent class.
• Any JComponent object can be added to any
Container object.
• Since class JComponent descends from class
Container, a JComponent object can be added to
another JComponent object.
Adding Components
• To add a component to a JFrame, use method
getContentPane to obtain the content pane, and the use
method add with the content pane as the calling object.
• example
Container contentPane = getContentPane();
Jlabel label = new Jlabel(“Click Here”);
contentPane.add(label);
• Add a button to a Panel:
JPanel buttonPanel = new JPanel();
JButton stopButton =
new JButton(“Stop”);
buttonPanel.add(stopButton);
Objects in Swing Containers
• Swing containers use three kinds of objects:
– the container class itself (such as a panel)
– the components (labels, buttons, panels, etc.)
– the layout manager.
• Typically, a GUI interface, and many subparts of
the GUI, will consist of these three kinds of
objects.
Text I/O using jTextField
• Create a text field with some initial text
JTextField textfield = new JTextField("Initial Text");
• Create a text field with some initial text and a default number of
columns.
// The number of columns controls the preferred width of the
component;
// each column is roughly the size of an M in the current font.
int cols = 30;
textfield = new JTextField("Initial Text", cols);
Text I/O using JTextArea
• Create a text area with some initial text
JTextArea textarea = new JTextArea("Initial Text");
• Create a text area with some initial text and a default number of
rows and columns.
// This number of rows and columns controls the preferred width and
height of the component;
// each row and column is rougly the size of an M in the current font.
int rows = 20;
int cols = 30;
textarea = new JTextArea("Initial Text", rows, cols);
Text box / Text area: Methods used
• Method getText returns the text written in an object of class
JTextArea.
• Method setText of class JTextArea changes the text in the text area
into whatever is provided as the argument to method setText.
• Limit the # of characters entered:
JTextField name = new JTextField(10);
• The number of characters (per line) is not absolute, but represents
the space needed for one ‘m’ character.
– Note: the lower case "m" is the widest character in most character sets
• For ReadOnly data: for a textbox named “Name”
– Name.setEditable(false);
• To Retrieve text
– Name.getText().trim();
• Note: check for NumberFormatException to check for unwanted
special characters (comma, - ,””) in “Name”
Quiz
• Create a text field object named “Name”
– Set the default value of the text as “put name”
– Set the length of this text field to 10