Download JFrame

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Object-Oriented S/W Development with Java CSCI 3381
Lessons 18 & 19:
Graphical User Interfaces
March 14, 26, 2013
1
Object-Oriented S/W Development with Java CSCI 3381
User Interface
The way in which user interacts with program
Separates “what” program does from “how” user
interacts with it
Television
• Function: Adjust volume, channels, color, etc.
• Interface:
– Manual controls
– Universal Remote
Automobile
• Function: Turn, accelerate, decelerate, stop
• Interface:
– Steering wheel
– Gas pedal
– Brake
2
Object-Oriented S/W Development with Java CSCI 3381
Powerball Example
Example PowerBallMachine class based on Powerball lottery where
person must correctly match 5 balls selected from collection of 55
balls.
PowerballMachine has single method called getOdds(int n, int k).
getOdds computes chances of correctly selecting k balls from
collection of size n.
Let’s look at two interfaces for our PowerBallMachine- a text based
interface and a graphical interface.
public class PowerBallMachine {
public int getOdds(int n, int k) {
int lotteryOdds = 1;
for (int i = 1; i <=k; i++) {
lotteryOdds = lotteryOdds * (n-i+1)/i;
}
return lotteryOdds;
}
}
3
Object-Oriented S/W Development with Java CSCI 3381
Powerball- Console Interface
public class PowerBallMain {
public static void main(String args[]) {
PowerBallMachine machine = new PowerBallMachine();
Scanner input = new Scanner(System.in);
System.out.println("Enter number of balls to pick from: ");
int n = input.nextInt();
System.out.println("How many balls do you want to draw? ");
int k = input.nextInt();
System.out.println("Odds of winning are 1 in " +
machine.getOdds(n, k));
}
}
4
Object-Oriented S/W Development with Java CSCI 3381
Powerball – Graphical User Interface
5
Object-Oriented S/W Development with Java CSCI 3381
Basic GUI Components
Original (pre-Java 2) GUI components - heavyweight:
Java 2's Swing GUI Components are lightweight:
rely on local platform's windowing system
each heavyweight component has a peer that oversees
interactions between component and local platform
result: platform-dependent appearance
written completely in Java
not "weighed down" by
platform's GUI capabilities
not necessarily good for graphics
Pros and Cons: see
http://dn.codegear.com/article/26970
6
Object-Oriented S/W Development with Java CSCI 3381
Swing Components
Frames
Scroll Panes
Panels
Tabbed Panes
Sun’s Java Tutorial
Split Panes
7
Object-Oriented S/W Development with Java CSCI 3381
Swing Components (cont.)
Lists
Progress Bars
Buttons
Combo Boxes
Labels
Text Boxes
Menus
Spinners
Sun’s Java Tutorial
Sliders
8
Object-Oriented S/W Development with Java CSCI 3381
Displaying Swing Components in Window
To use Swing Components, must provide framework
for displaying them
Most prevalent framework for displaying Swing
Components is the Window
Most windows you will create are an instance of class
JFrame or a subclass of JFrame
JFrame provides the basic attributes and behaviors of
a window
title bar at the top of the window
buttons to minimize, maximize, and close the window
9
Object-Oriented S/W Development with Java CSCI 3381
Anatomy of a Frame
10
Object-Oriented S/W Development with Java CSCI 3381
Constructing Window Containing Swing Components
Define xxxFrame class as extension of JFrame
For
JFrame used to hold labeled text:
// LabelFrame.java
10 public class LabelFrame extends JFrame
11 {
42 }//end class LabelFrame
Add class instance variable for desired Swing component
10 public class LabelFrame extends JFrame
11 {
12
private JLabel label1;
13
private JLabel label2;
42 }//end class LabelFrame
11
Object-Oriented S/W Development with Java CSCI 3381
Constructing Window Containing Swing Components
Use class constructor to add component to frame
10 public class LabelFrame extends JFrame
11 {
12
private JLabel label1;
13
private JLabel label2;
17
public LabelFrame()//LabelFrame constructor
18
{
19
super(“Testing JLabel”); //Creates bare JFrame
20
setLayout( new FlowLayout());
22
label1 = newJLabel(“Label with text”);
24
add( label1); //add label1 to JFrame
41
}//end LabelFrame constructor
42 }//end class LabelFrame
12
Object-Oriented S/W Development with Java CSCI 3381
Creating and Displaying LabelFrame Window
Create test class which creates object of class
LabelFrame, defines action upon window closure, sets
window size, and makes it viewable
1 // LabelTest.java
3 import javax.swing.JFrame;
4
5 public class LabelTest
6 {
7
public static void main( String args[] )
8
{
// create LabelFrame
9
LabelFrame labelFrame = new LabelFrame( );
10
labelFrame.setDefaultCloseOperation
( JFrame.EXIT_ON_CLOSE );
11
labelFrame.setSize(275, 180 );
12
labelFrame.setVisible( true );
13
}// end main
14 }// end class LabelTest
13
Object-Oriented S/W Development with Java CSCI 3381
Swing Components
Interact with your Program
PowerballMachine
getOdds(int n, int k)
14
Object-Oriented S/W Development with Java CSCI 3381
Event Handling
Graphical User Interface
Widget
Registered Listeners
Event
Object A
Object B
Object A
Object B
Object C
Object C
Event Listeners
or
Event Handlers
15
Object-Oriented S/W Development with Java CSCI 3381
Creating & Sending Events
GUI components that can change state cause “events”
to happen when a change in state occurs
JButtons – ActionEvent
JTextField – ActionEvent
JLists – ListSelectionEvent
JCheckBox – ItemEvent
plus many, many more...
All have a method which allows objects to register as
an event listener
addxxxListener(xxxListener x);
16
Object-Oriented S/W Development with Java CSCI 3381
Event Listeners/Handlers
Objects become event listeners by implementing the
appropriate interface that allows them to register with
the GUI component that causes events to be generated
Ex: JButton is a GUI component that causes an event to
be generated every time it is pressed
JButton b = new JButton(“Button #1”);
By virtue of being a JButton,
Generate ActionEvents
b generates ActionEvents
addActionListener(ActionListener a);
17
Object-Oriented S/W Development with Java CSCI 3381
Event Listeners/Handlers (cont.)
Any object implementing ActionListener interface can
register with JButton to be notified when button changes state
(is pressed)
public interface ActionListener {
void actionPerformed(ActionEvent e);
}
By implementing the
ActionListener
interface, MyObject
becomes an
ActionListener
public class MyObject implements ActionListener {
...
public void actionPerformed(ActionEvent e) {
System.out.println(“Don’t press the button!”);
}
}
Since mo is an ActionListener,
it can register with JButton b
MyObject mo = new MyObject();
b.addActionListener(mo);
18
Object-Oriented S/W Development with Java CSCI 3381
Button Example
Let’s start with a very simple example of a Frame that
contains two GUI components
a button
a label.
When button is pressed, message displayed at console
19
Object-Oriented S/W Development with Java CSCI 3381
GuiTest: JButton Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuiTest {
public static void main(String[] args) {
JFrame j = new JFrame("Title");
j.setSize(275, 170);
Container c = j.getContentPane();
c.setLayout(new FlowLayout());
JButton b = new JButton("I Believe");
b.addActionListener(new MyActionListener());
c.add(b);
JLabel lab = new JLabel(“Push the button!");
c.add(lab);
j.setVisible(true);
j.addWindowListener(new MyWindowAdapter());
}
}
20
Object-Oriented S/W Development with Java CSCI 3381
GuiTest: JButton Example (cont.)
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Window closed...Exiting
Program");
System.exit(0);
}
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed");
}
}
21
Object-Oriented S/W Development with Java CSCI 3381
FlowLayout: Simplest Layout Manager
Function main() from GuiTest example creates GUI
component objects and attaches them to the JFrame:
Layout set before any components attached to Jframe
c.setLayout(new FlowLayout());
GUI components are placed on JFrame left to right in the
order in which attached to JFrame (FlowLayout).
Wrap to next line when edge reached.
Other layout managers:
Border (N,S,E,W, Center) and,
Grid (like a 2-D array)
GridBagLayout (most flexible/complex layout manager)
22
Object-Oriented S/W Development with Java CSCI 3381
GuiTest Example that uses Flow Layout
public class GuiTest {
public static void main(String[] args) {
JFrame j = new JFrame("Title");
j.setSize(275, 170);
Container c = j.getContentPane();
c.setLayout(new FlowLayout());
JButton b = new JButton("I Believe");
b.addActionListener(new
MyActionListener());
c.add(b);
main( ) creates and attaches GUI components to the user
interface
c.add(b) adds component to contentPane as per layout
manager.
23
Object-Oriented S/W Development with Java CSCI 3381
GUITest Revisited
Program works fine, but I want to change the structure
so that we lay out GUI in constructor vice in main
method.
Along the way we’ll also
Move ActionListener and WindowAdapter classes inside
GuiTest class
Get rid of JFrame created in main and make GuiTest the
JFrame by having GuiTest extend JFrame
Reason for doing this may not be clear right now since
our GUI is extremely simple, but as they get more
complicated these changes will help with scope issues
and make it easier to add increasingly sophisticated
behavior.
24
Object-Oriented S/W Development with Java CSCI 3381
GuiTest extends JFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
Compare this version to
previous. Things to note:
Explicit definition of JFrame is
public class GuiTest extends JFrame {
gone. GuiTest extends JFrame
so it is the JFrame.
private Container c;
Most of what was in main is
public GuiTest(String t) {
now in GuiTest constructor.
super(t);
Title for frame is passed via
setSize(275, 170);
constructor using super.
c = getContentPane();
c.setLayout(new FlowLayout());
JButton b = new JButton("I Believe");
b.addActionListener(new MyActionListener());
c.add(b);
JLabel lab = new JLabel("Push the button!");
c.add(lab);
setVisible(true);
addWindowListener(new MyWindowAdapter());
}
public static void main(String[] args) {
GuiTest g = new GuiTest("GuiTest Title");
}
25
Object-Oriented S/W Development with Java CSCI 3381
GuiTest: Inner Classes
Compare this version to
previous. Things to note
(cont.):
MyWindowAdapter and
MyActionListenter classes
moved inside class GuiTest
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Window closed...Exiting
Program");
System.exit(0);
}
}// end class MyWindowAdapter
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Pressed");
}
}// end class MyActionListener
}// end class GuiTest
26
Object-Oriented S/W Development with Java CSCI 3381
GuiTest: Count the button clicks
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GuiTest3 extends JFrame {
private Container c;
private int x = 0;
JLabel lab;
public GuiTest3(String t) {
super(t);
setSize(275, 170);
c = getContentPane();
c.setLayout(new FlowLayout());
JButton b = new JButton("I Believe");
b.addActionListener(new MyActionListener());
c.add(b);
lab = new JLabel("Push the button!");
c.add(lab);
setVisible(true);
}
27
Object-Oriented S/W Development with Java CSCI 3381
GuiTest: Count the button clicks (cont.)
public static void main(String[] args) {
GuiTest3 g = new GuiTest3("GuiTest Title");
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
x++;
if (x == 1) {
lab.setText("First Time!");
System.out.println("Button pressed for the first time!");
}
else if (x < 10) {
lab.setText(x + " times.");
System.out.println("Button Pressed " + x + " times.");
}
else {
lab.setText("Enough already...stop!");
System.out.println("Button Pressed " + x + " times.");
}
}
}
}// end class GuiTest3
28
Object-Oriented S/W Development with Java CSCI 3381
Summary
User Interface Example: Console vs. GUI
Basic GUI Components: AWT vs. Swing
Swing Component Examples
Displaying Swing Components in Window
Anatomy of a Frame
Constructing Window Containing Swing Components
Event Handling: Event Listeners/Handlers
FlowLayout: Simplest Layout Manager
Inner Classes
29