java swing 4 th april 2008 cs 180 department of computer science, purdue university

45
Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Post on 21-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Java Swing4th April 2008

CS 180

Department of Computer Science,

Purdue University

Page 2: Java Swing 4 th 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.

Page 3: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Controls on GUI

• WINDOW

• FRAME

• MENU

• BUTTON

• TEXT BOX

• COMBO BOX

Many more….

Page 4: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 5: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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

Page 6: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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(); //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); } }

A Frame

This colored area is the content pane

Example

Page 7: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Exploring JFrame : Some methods

•A window class normally is derived from class JFrame.

•A derived window class inherits all the methods from class JFrame.

Page 8: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Window Listeners

• A window listener listens to events from a window, such as a click on the close-window button.

• A window listener is registered when it becomes associated with the object(s) to which it listens.

Page 9: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Clicking the Close-Window Button

Page 10: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 11: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Example Codeimport 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…………………… //set listener

makeWindowListner myListener= new makeWindowListner();

myWindow.addWindowListener(myListener); } • }

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);

System.exit(0); } }

Listener Class

Page 12: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Example: OutputStep 1: user clicks this close button

Step 2: user will see this dialog box

Step 3: window is closed

Page 13: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Methods of Class WindowAdapter

Some examples:

Page 14: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 15: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

What to Import

• It may be simpler to useimport 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.

Page 16: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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

Page 17: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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);

andcontent.add(label3, “Center”);

and (for center ONLY)content.add(label3);

Page 18: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Some Layout Managers

Page 19: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 20: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Adding Buttons

• A button is created usingJButton Button_Name = new

JButton(“Button_Label”);

• A button is added to a container usingContainer_Name.add(Button_Name);

Page 21: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Adding Buttons, cont.

Page 22: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Adding Buttons, cont.

Page 23: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 24: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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

Page 25: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.)

Page 26: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Buttons and an Action Listener

Page 27: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

The actionPerformed Method

• An actionListener class must have a method named actionPerformed that has one parameter of type ActionEvent.

• syntaxpublic void actionPerformed(ActionEvent e)

{

Code_for_Actions_Performed

}

Page 28: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 29: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

The Model-View-Controller Pattern

Page 30: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 31: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 32: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

Method setActionCommand, cont.

• exampleJButton 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.

Page 33: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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

Page 34: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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)

Page 35: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 36: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

The JPanel Class, cont.

Page 37: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

The JPanel Class, cont.

Page 38: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 39: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 40: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

• exampleContainer 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);

Page 41: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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.

Page 42: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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);

Page 43: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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);

Page 44: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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”

Page 45: Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University

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