Introduction to GUI Programming with Java: AWT and Swing

Download Report

Transcript Introduction to GUI Programming with Java: AWT and Swing

Introduction to GUI
Programming with Java
Graphical User Interfaces
With AWT and Swing
Towson University 2013.
*Ref: http://chortle.ccsu.edu/java5/index.html
Graphical User Interface
GUI
- Users interact with application programs using graphical components such
as buttons, text boxes, and menus as well as console.
- Hard to write a GUI application, but most of functions are provided by a set
of classes called Swing
• Swing
– A large package
– Composed of graphical components:
• Windows
• Buttons
• Menus
• Text fields
– Built on the fundamental classes of the Abstract Windowing
Toolkit (AWT)
– Come with recent Java releases
3
Events
- Users controls the application by interacting with the graphical components,
generating events.
• GUI Events
–
–
–
–
Mouse clicking on a button
Making a choice from a menu
Entering text in a text box
Dragging a scroll bar
• Event-driven programming
– Users cause events on the GUI components and the program
responds to these events.
– Programming by organizing the GUI components contained in the
Swing package.
4
GUI Program
● GUI Program
– Graphical Components: Swing objects or extended one
– Listener methods: Java methods the interface GUI components
with the application tasks by calling application methods
– Application methods: Java methods performing specific functional
tasks
5
GUI Component
Container Classes
● Window
– A fundamental container
– Includes other GUI components
– Ex) Browser is a window (container) containing buttons, menus,
slides, icons, and other GUI components.
• Container
– A container can contain another container.
– Ex) Main window contains frames which contain other
components.
7
Java Classes
● AWT and Swing
– Inherited from Java Object class
• AWT
– Contains the fundamental classes used for constructing GUIs.
– Component class is defined as the base abstract class.
– AWT classes: Button, Canvas, and Container inherited from
Component class
• Swing classes
– Swing JComponent(derived rom AWT Container class)
• one of the base class of Swing
– Swing JFrame(from AWT Frame class)
• Usually the main container for a GUI application
8
Swing component hierarchy
• Graphical components in Java form an inheritance hierarchy:
java.lang.Object
+--java.awt.Component
+--java.awt.Container
|
+--javax.swing.JComponent
|
+--javax.swing.JButton
|
+--javax.swing.JLabel
|
+--javax.swing.JMenuBar
|
+--javax.swing.JOptionPane
|
+--javax.swing.JPanel
|
+--javax.swing.JTextArea
|
+--javax.swing.JTextField
|
+--java.awt.Window
+--java.awt.Frame
+--javax.swing.JFrame
• When doing GUI programming, always import these packages:
import java.awt.*;
import javax.swing.*;
9
Inheritance Hierarchy
Java Programming: Program Design Including Data Structures
1010
Java GUI: AWT and Swing
• Sun's initial idea: create a set of classes/methods that can be
used to write a multi-platform GUI (Abstract Windowing
Toolkit, or AWT)
– problem: not powerful enough; limited; a bit clunky to use
• Second edition (JDK v1.2): Swing
– a newer library written from the ground up that allows much
more powerful graphics and GUI construction
• Drawback: Both exist in Java now; easy to get them mixed up;
still have to use both sometimes!
11
JComponent Classes
● Container family
–
–
–
–
–
Can
Can
Can
Can
Can
contain components
be placed inside containers
be displayed on the monitor
generate events
register event listeners
• Swing classes
– All Swing classes are descendants of Container class.
– In addition to JComponent, JLabel, JPanel, JSlider,
JTextComponent, JButton, …
12
JFrame class
● JFrame
– Represents the window of a GUI application program
– Can hold the components and methods of your application
• Methods
–
–
–
–
setSize()
setBounds()
setVisible()
setDefaultCloseOperation()
● Frame in Java
– A window containing borders, buttons, and other features.
13
JFrame example 1
• A simple program that creates and shows a JFrame:
import javax.swing.*;
public class SimpleFrame {
public static void main(String[] args) {
JFrame frame = new JFrame(“SimpleFrame”);
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}
• Graphical output:
14
JFrame example 2
import java.awt.*;
import javax.swing.*;
public class SimpleFrame2 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setForeground(Color.WHITE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(new Point(100, 50));
frame.setSize(new Dimension(300, 120));
frame.setTitle("A frame");
frame.setVisible(true);
}
}
• Graphical output:
15
JFrame
A frame is a graphical window that can
be used to hold other components
• public JFrame()
public JFrame(String title)
Creates a frame with an optional title.
• public void setTitle(String text)
Puts the given text in the frame’s title bar.
• public void setDefaultCloseOperation(int op)
Makes the frame perform the given action when it closes. Common value:
JFrame.EXIT_ON_CLOSE
• public void add(Component comp)
Places the given component or container inside the frame.
– How would we add more than one component to the frame?
• NOTE: Call setVisible(true) to make a frame appear on screen after creating it.
16
JButton class
● JButton
– Inherited from AbstractButton which is inherited from
JComponent
– Can contain other components
– ButtonFrame and ButtonDemo
17
Components example
• This program attempts to show 2 buttons:
import java.awt.*;
import javax.swing.*;
public class ComponentsExample1 {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(new Dimension(300, 100));
frame.setTitle("A frame");
JButton button1 = new JButton();
button1.setText("I'm a button.");
button1.setBackground(Color.BLUE);
frame.add(button1);
JButton button2 = new JButton();
button2.setText("Click me!");
button2.setBackground(Color.RED);
frame.add(button2);
frame.setVisible(true);
}
}
18
Changing layouts
• We can correct the program's appearance by changing the
frame's layout manager .
• Change the layout by calling the setLayout method on the
frame and passing a layout manager object.
– We will see several layout managers later.
– We'll use one called a FlowLayout, which sizes each component
to its preferred size and positions them in left-to-right rows.
– If the following line is added to the preceding program just before
calling setVisible(true), its appearance will be:
frame.setLayout(new FlowLayout());
19
Action events with
ActionListener
Event-driven programming
• program's execution is indeterminate
• on-screen components cause events to occur when they are
clicked / interacted with
• events can be handled, causing the program to respond,
driving the execution thru events (an "event-driven" program)
21
Java Event Hierarchy
java.lang.Object
+--java.util.EventObject
+--java.awt.AWTEvent
+--java.awt.event.ActionEvent
+--java.awt.event.TextEvent
+--java.awt.event.ComponentEvent
+--java.awt.event.FocusEvent
+--java.awt.event.WindowEvent
+--java.awt.event.InputEvent
+--java.awt.event.KeyEvent
+--java.awt.event.MouseEvent
• import java.awt.event.*;
22
Action events: ActionEvent
• most common / simple event type in Swing
• represent an action occurring on a GUI component
• created by:
–
–
–
–
–
button clicks
check box checking / unchecking
menu clicks
pressing Enter in a text field
etc.
23
Listening for events
• attach a listener to the component
• listener’s appropriate method will be called when event occurs
(e.g. when the button is clicked)
• for Action events, use ActionListener
• ActionListeners are event handlers to define what should be
done when an user performs certain operation.
24
Writing Action Listener
• Declare an event handler class by specifying that the class
either implements an ActionListener interface or extends a
class that implements an ActionListener interface.
public class MyHandler implements ActionListener {
…
}
• Register an instance of the event handler class as a listener on
one or more components
someComponent.addActionListener(instanceOfMyHandler);
• ActionListener interface is special, enforcing the inclusion of the
method, actionPerformed().
Public void actionPerformed(ActionEvent e) {
…
}
25
Writing an ActionListener
// part of Java; you don't write this
public interface ActionListener {
public void actionPerformed(ActionEvent event);
}
// Prints a message when the button is clicked.
public class MyActionHandler
implements ActionListener {
public void actionPerformed(ActionEvent event){
JButton.showMessageDialog(null,
"An event occurred!");
}
}
26
Attaching an ActionListener
import java.awt.*;
import java.awt.event.*;
public class MyAH extends Frame implements WindowListener,ActionListener {
TextField text = new TextField(20);
Button b;
private int numClicks = 0;
public static void main(String[] args) {
MyAH myWindow = new MyAH("My first window");
myWindow.setSize(350,100);
myWindow.setVisible(true);
}
public MyAH(String title) {
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b = new Button("Click me");
add(b);
add(text);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
numClicks++;
text.setText("Button Clicked " + numClicks + " times");
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
...
} // end of class MyAH
27
Text Field Example
• Capturing user input from a text field
public void actionPerformed(ActionEvent e) {
String textFieldValue = text.getText();
text.setText(textFieldValue + " PASSED.....");
}
28
JTextField methods
• getText()
• setText()
29
import
import
import
import
import
import
java.awt.*;
java.awt.event.*;
javax.swing.JTextField;
javax.swing.JTextArea;
javax.swing.JButton;
javax.swing.JLabel;
public class MyAH extends Frame implements WindowListener,ActionListener {
JTextField text = new JTextField(20);
JLabel label1 = new JLabel("AWT Button Example");
Button b;
private int numClicks = 0;
JLabel label2 = new JLabel("Please type numeric expression");
JTextField input = new JTextField(20);
JButton bSubmit;
//ButtonFrame frm = new ButtonFrame("Button Demo");
JTextArea output = new JTextArea(20, 20);
public static void main(String[] args) {
MyAH myWindow = new MyAH("My first window");
myWindow.setSize(350,250);
myWindow.setLayout(new FlowLayout());
myWindow.setVisible(true);
}
30
public MyAH(String title) {
super(title);
setLayout(new FlowLayout());
addWindowListener(this);
b = new Button("Click Me!");
bSubmit = new JButton("Submit"); // construct a JButton
add(label1);
add(b);
add(text);
add(label2);
add(input);
add(bSubmit);
//input.setText("Type numeric expression. ");
add(output);
b.addActionListener(this);
MyActionHandler calcHandler = new MyActionHandler();
bSubmit.addActionListener(calcHandler);
}
31
public void actionPerformed(ActionEvent e) {
numClicks++;
String textFieldValue = text.getText();
text.setText("Button has been pressed " + numClicks + " times.");
/*
String inputTextFieldValue = inputTextFieldValue = input.getText();
Double outputValue = calculate(inputTextFieldValue);
input.setText(inputTextFieldValue);
//output.setText("Result equals" + i*100);
output.setText("Result equals " + inputTextFieldValue);
//output.setText("Result equals" + outputValue);
*/
}
public double calculate(String exp) {
return 100;
}
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
32
public
public
public
public
public
public
void
void
void
void
void
void
windowOpened(WindowEvent e) {}
windowActivated(WindowEvent e) {}
windowIconified(WindowEvent e) {}
windowDeiconified(WindowEvent e) {}
windowDeactivated(WindowEvent e) {}
windowClosed(WindowEvent e) {}
public class MyActionHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String inputTextFieldValue = input.getText();
Double outputValue = calculate(inputTextFieldValue);
input.setText(inputTextFieldValue);
output.setText("Result equals " + inputTextFieldValue);
}
} // end of class MyActionHandler
} // end of class MyAH
33