Intro to Graphical User Interface (GUI) with Swing, Event Handling.

snottybugbearΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 3 χρόνια και 5 μήνες)

82 εμφανίσεις

Handout 6 CS280 – OO Application Development–Spring’13 Page 1 of 6


Handout 6

Intro to Graphical User Interface (GUI) with Swing, Event Handling.

The Swing library (javax.swing.*)
(h
ttp://java.sun.com/docs/books/tutorial/ui/features/compWin.html)

Contains classes that implement User Interface components

Buttons, radio buttons, text fields, etc

Extends an earlier library: AWT

- 1 -
Handout 6 CS280 – OO Application Development–Spring’13 Page 2 of 6

Need a Container object in which to place UI components - will use JFrame.
JFrame
– a window that cannot be put inside another window
– components can be added to a frame’s content pane (getContentPane() instance
method) using method add
First, a simple example:
Create a window with a Label, TextField and 2 buttons, Hi and Exit.

/** * Simple Java program displaying a window. */
import java.awt.Container
;
import java.awt.FlowLayout;
import javax.swing.*;

public class SimpleFrame
extends JFrame {

private JButton hi = new JButton("Hi");
private JButton exit = new JButton("Exit");
private JTextField tf = new JTextField("<Name goes here>", 10);

public SimpleFrame (){
// recall, the no arg
constructor of superclas
,
// i.e. JFrame() gets called here.
// or call another one: e,g, super("Call me Foo
");
this.setSize(450, 100);
this.setTitle("Simple Frame example");
this.setLocation(300, 300);
// set it so that closing the window will terminate program
this.setDefaultCloseOperation(EXIT_ON_CLOSE);

// tell the frame how to lay out components
this.setLayout(new FlowLayout());

// add components
this.add(new JLabel("Enter your name"));
this.add(tf);
this.add(hi);
this.add(exit);

this.setVisible(true);
}

public static void main(String[] args) {
// instantiate the class, will display a window
new SimpleFrame();

}

}

Common pitfalls:

Don’t’ forget to set a layout to the frame

Don’t forget to make the frame visible
Otherwise the window will not show all components or may not show at all!
- 2 -
Handout 6 CS280 – OO Application Development–Spring’13 Page 3 of 6

Examples: some other things that are commonly done:
JLabel:
JLabel l = new JLabel(“Put text here”);

l.setText(“Change it here”);


JTextFields:

JTextField t1 = new JTextField(25);
JTextField t2 = new JTextField(“Balance”, 20);

t1.setText(“Deposit”); // set content
String s = t2.getText(); // retrieve content
t1.setEditable(false); // user can’t change contents


JTextArea:
JTextArea a1 = new JTextArea(10, 25); // rows, cols
JTextArea a2 = new JTextArea(“list accounts: ”, 10, 25);

a1.setText(“account 1”); // replace content
a1.append(“account 2”); // append to content
a2.append(“account 1”); // append to content
a1.setEditable(false); // user can’t change contents

JList:
JList lst = new JList( …an array of items … )
;

Object obj = lst.getSelectedValue();
Other metods:
lst.getSelectedIndex()
lst.setSelectedValue()
lst.setListData( Object [] items) and more


JRadioButton and ButtonGroups:

JRadioButton add = new JRadioButton("Addition", true);
JRadioButton subtract=new JRadioButton("Subtraction", false);

The
isSelected()
method returns true if the RadioButton is selected, and false
otherwise.

Add a component of type
ButtonGroup
to ensure to groups radio buttons so only 1 can be
selected at any given time:

ButtonGroup operations = new ButtonGroup();

operations.add(add);
operations.add(subtract);


Take a look at the Java Swing Tutorial online at
http://docs.oracle.com/javase/tutorial/uiswing/index.html


- 3 -
Handout 6 CS280 – OO Application Development–Spring’13 Page 4 of 6


Event Handling


An event can be defined as a signal to the program that something has happened.

The event object is generated by external user actions such as mouse movements, mouse
clicks, and keystrokes, or by the operating system, e.g. a timer event.

Source Event Type
User Action Object Generated

Click a button JButton ActionEvent
Click a check box JCheckBox ItemEvent, ActionEvent
Click a radio button JRadioButton ItemEvent, ActionEvent
Press return on a text field JTextField ActionEvent
Select a new item JComboBox ItemEvent, ActionEvent
Window opened, closed, etc. Window WindowEvent
Mouse pressed, released, etc. Component MouseEvent
Key released, pressed, etc. Component KeyEvent

User input through UI Components is processed via event-handling mechanism:
• Program waits for events to occur and then responds
• Firing an event—when a source object generates an event
• Listener—object that receives a notification of an event occurring.
• Event handler—method that gets called by listener in response to an event

Listener Object must implement the appropriate Event handler method, specified by an in an
appropriate listener interface (e.g. ActionListener, ItemListener, MouseEventListener, etc..)


An event object contains whatever properties are pertinent to the event (the source
component that fired the event, the time, etc…)

You can identify the source object of the event using the getSource()
instance method in the
EventObject
class

Handling ActionEvents (generated by button-clicks, presses of Enter in TextArea, etc..)

Register
receiver
as the listener object for the Button (or other source object).

button.addActionListener(receiverObject);
• The listener object must implement the
ActionListener
interface, i.e. provide
definition of method
public void actionPerformed(ActionEvent e)
Simple example: extending the SimpleFrame to react to ActionEvents




- 4 -
Handout 6 CS280 – OO Application Development–Spring’13 Page 5 of 6

/** * Simple Java program displaying a window. Now made to respond to commands */
import java.awt.Container
;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SimpleFrame
extends JFrame implements ActionListener{

private JButton hi = new JButton("Hi");
private JButton exit = new JButton("Exit");
private JTextField tf = new JTextField(10);

public SimpleFrame (){
this.setSize(450, 100);
this.setTitle("Simple Frame example");
this.setLocation(300, 300);
// set it so that closing the window will terminate program
this.setDefaultCloseOperation(EXIT_ON_CLOSE);

// tell the frame how to lay out components
this.setLayout(new FlowLayout());

// add components
this.add(new JLabel("Enter your name"));
this.add(tf);
this.add(hi);
this.add(exit);

// register this as a listener to action events
// from the following components
tf.addActionListener(this);
hi.addActionListener(this);
exit.addActionListener(this);

this.setVisible(true);
}

/** Method required by the ActionListener interface
* Is passed in an event as a parameter.
* Performs an action based on the source of event. */

public void actionPerformed(ActionEvent event) {

if (event.getSource() == this.hi){ // hi
button was pressed
System.out.println("Hi, " + tf.getText() + "!");}
else if (event.getSource() == this.exit) {
// exit button was pressed
System.out.println("Bye, " + tf.getText() + "!");
System.exit(0);}
else if (event.getSource() == this.tf) {
// user pressed enter in the text field
System.out.println("Nice to meet you, " + tf.getText() + "!"); }
}

public static void main(String[] args) {
- 5 -
Handout 6 CS280 – OO Application Development–Spring’13 Page 6 of 6

- 6 -
// instantiate the class, will display a window
new SimpleFrame();
}

}