10/9/2014
1
Method OverloadingReview
Method Overloading (1/4)● Can define multiple methods
of same name within a class,as long as method signaturesare different
● Example: java.lang.Math● static method max takes in
two numbers and returns thegreater of the two
● There are actually three maxmethods-- one for ints, onefor floats, one for doubles
// this is an approximation of what Math’s// three max methods look likepublic class Math {
// other code elided
public static int max(int a, int b) {// return max of two ints
}
public static float max(float a, float b) {// return max of two floats
}
public static double max(double a,double b){
// return max of two doubles}
}
● Methods in same class withsame name but differentparameter lists
● When calling an overloadedmethod, Java infers whichmethod you mean based onparmeter list
● Thus cannot have two methodswith identical signatures butdifferent return types—compilererror because Java can’tdetermine which to call!
// this is an approximation of what Math’s// three max methods look likepublic class Math {
// other code elided
public static int max(int a, int b) {// return max of two ints
}
public static float max(float a, float b) {// return max of two floats
}
public static double max(double a,double b){
// return max of two doubles}
}
Method Overloading (2/4)● Be careful not to confuse
overloading and overriding!o override an inherited
method in a subclass: thesignatures (name; number,types, and order ofparameters) must be thesame
o overload methods in thesame class: names aresame, but signatures mustbe different
// this is an approximation of what Math’s// three max methods look likepublic class Math {
// other code elided
public static int max(int a, int b) {// return max of two ints
}
public static float max(float a, float b) {// return max of two floats
}
public static double max(double a,double b){
// return max of two doubles}
}
Method Overloading (3/4)
10/9/2014
2
● If neither overriding nor overloading: Can use same name,indeed signatures for methods in different classes
o Java can differentiate by type of instance on whichmethod is called during method resolution
o for example: if classes Car and Dog both have a movemethod that takes in one parameter of type int, Javaknows to use the Dog’s move when called on aninstance of Dog:
Dog dog = new Dog();
Car car = new Car();
dog.move(1); //Dog’s move method is called.car.move(1); //Car’s move method is called.
Method Overloading (4/4) Method Overloading: Constructors● Even constructors can be
overloaded! Wardrobe classhas multiple constructors
● A String (java.lang.String)is a sequence of alphanumericcharacters, including space!
● Example:String s = “CS15 Rocks!”;
● Can use System.out.printlnto print any string you want:
System.out.println(s);
public class Wardrobe {private String _top;private String _bottom;
public Wardrobe(String top, String bottom) {_top = top;_bottom = bottom;
}
public Wardrobe(String top) {_top = top;_bottom = “Jeans”;
}
public Wardrobe() {_top = “T-Shirt”;_bottom = “Jeans”;
}}
Method Overloading: Example
public class Plastic {
public Plastic(BurnBook myBurnBook) {DirtySecret secret = myBurnBook.getDirtySecret();this.backStab(secret);
}
public void backStab(DirtySecret secret) {String victim = secret.getVictim(); //find out whose secret it isthis.backStab(victim, secret);
}
public void backStab(String victim, DirtySecret secret) {//code to backstab elided (we don’t teach you how to backstab!)
}//other methods elided}
● An overloaded method can call other overloaded methodsLecture 9
Intro to Swing0 of 95
10/9/2014
3
What is Swing?● Swing is an API (Application Programming
interface)o part of core Java libraryo used to create applications with 2D graphics
● Frequently used classes in javax.swing packageo javax.swing.JFrame– the main window used
by your appo javax.swing.JPanel-- a canvas that contains
graphical componentso javax.swing.JButton-- a clickable button
1 of 95
JPanelJButtons
JFrame
Creating Applications from Scratch
● Until now, TAs took care of graphicalcomponents for you
● Support code created JFrame, JPanels, allgraphical components
● From now on, you’re in charge of this!
2 of 95
Graphical User Interfaces (GUIs)
● GUIs provide a user-controlled (i.e.,graphical) way to sendmessages to a systemof objects
● You’ll use Swing tocreate your own GUIsthroughout the semester
3 of 95
Pixels and Coordinate System
● The screen is a grid ofpixels (tiny dots)
● Integer Cartesian plane with:o origin in upper-left cornero y-axis increasing downwardo corresponds to Latin-based
languages’ writing order
(0, 0)
Y
X
pixels 4 of 95
10/9/2014
4
Pixels and Coordinate System
● When working with Swing,you’ll be able to set the sizeand location of differentcomponents (panels, buttons,etc.) in pixels
● The “location” of eachcomponent will be thelocation of its top left corner
(0, 0)
Y
X
pixels 5 of 95
Creating GUIs with Swing● Pattern: instantiate the
Swing components youneed and add them tographical containers
● Start with JFrame
JFrame
● Add JPanel to JFrame
● Add JButtons,JLabels, etc. to JPanel
JPanel
Hello, World!JLabel
JButtons
6 of 95
Creating GUIs with Swing● Swing uses a default
layout to arrangecomponents in a JFrameor JPanel
● We’ll learn how tocustomize layout later inlecture
● For now, let Swing do itfor us
JFrame
JPanel
Hello, World!JLabel
JButtons
7 of 95
Our First Swing Application
● Spec: app that contains textreading “CS15 Rocks!” andbutton that randomlychanges the text’s color withevery click
● Useful classes: JFrame,JPanel, JLabel, JButton,and ActionListener
JFrame
JLabel
JButtonJPanel
8 of 95
10/9/2014
5
DEMO: ColorTextApp
9 of 95
JFrame
JLabel
JButtonJPanel
Process1. Create a top-level App class that
contains an instance of JFrame2. Create a subclass of JPanel that
contains an instance of JButton andan instance of JLabel
3. Add an instance of your JPanelsubclass to the JFrame
4. Set up an ActionListener thatchanges the label’s color each timethe button is clicked
10 of 95
JFrame
JLabel
JButtonJPanel
● This is our top-levelclass
● It contains the JFrame(window in which theapp will display) as acomponent
public class ColorTextApp {
public ColorTextApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}
public static void main(String[] args) {new ColorTextApp();
}}
Top-level Class: ColorTextApp
11 of 95
● First we instantiate aJFrame, which we store inlocal variable frame
● Note: these slides will omitimport statements at top offile
Top-level Class: ColorTextApppublic class ColorTextApp {
public ColorTextApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}
public static void main(String[] args) {new ColorTextApp();
}}
12 of 95
10/9/2014
6
● Next we call setDefaultCloseOperation onour JFrame
● This method specifies what happens whenuser hits “x” in corner of the JFrame
● Pass in constant JFrame.EXIT_ON_CLOSEas an argument so app will quit when wepress the “x”
● Swing magic keeps JFrames and theircontents alive as long as the “x” is notpressed, so they will not be “garbage-collected!” (Java GC’s variables when theygo out of scope – cease to exist)
Top-level Class: ColorTextApppublic class ColorTextApp {
public ColorTextApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}
public static void main(String[] args) {new ColorTextApp();
}}
13 of 95
● Finally, we call the methodsetVisible on our JFrame
● Pass in boolean value trueas an argument
● This makes the JFrame showup!
● Pro tip: Always call thismethod last to avoid nastylayout bugs
Top-level Class: ColorTextApppublic class ColorTextApp {
public ColorTextApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}
public static void main(String[] args) {new ColorTextApp();
}}
14 of 95
Process1. Create a top-level App class that
contains an instance of JFrame2. Create a subclass of JPanel that
contains an instance of JButtonand an instance of JLabel
3. Add an instance of your JPanelsubclass to the JFrame
4. Set up an ActionListener thatchanges the label’s color each timethe button is clicked
15 of 95
JFrame
JLabel
JButtonJPanel
● The classColorTextPanel “is a”JPanel: our canvas thatmay contain other SwingGUI components
● We’ve specialized thisclass to contain anddisplay a JLabel and aJbutton (local vars)
public class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JButton button = new JButton("Random Color");
Dimension panelSize = new Dimension(150, 75);this.setPreferredSize(panelSize);this.add(label);this.add(button);
}}
JPanel Subclass: ColorTextPanel
16 of 95
10/9/2014
7
JPanel Subclass: ColorTextPanel
public class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JButton button = new JButton("Random Color");
Dimension panelSize = new Dimension(150, 75);this.setPreferredSize(panelSize);this.add(label);this.add(button);
}}
17 of 95
● First, we instantiate aJLabel and JButton
● In each case, we pass ina String as an argument
● This String is the text wewant the label/button todisplay○ Here we pass the
string as a “literal”;could also pass astring variable
● Now we set the “preferredsize” of our panel
● First, instantiate a Dimension(object that represents awidth and height, in pixels)
● First argument is width,second is height
● Then call methodsetPreferredSize on panel,passing in the Dimension asan argument
JPanel Subclass: ColorTextPanel
public class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JButton button = new JButton("Random Color");
Dimension panelSize = new Dimension(150, 75);this.setPreferredSize(panelSize);this.add(label);this.add(button);
}}
18 of 95
● Finally, we add the labeland button to the panel bycalling the panel’s addmethod
● This is a necessary stepfor the label and button toshow up!
The ColorTextPanel class
public class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JButton button = new JButton("Random Color");
Dimension panelSize = new Dimension(150, 75);this.setPreferredSize(panelSize);this.add(label);this.add(button);
}}
19 of 95
Process1. Create a top-level App class that
contains an instance of JFrame2. Create a subclass of JPanel that
contains an instance of JButton andan instance of JLabel
3. Add an instance of your JPanelsubclass to the JFrame
4. Set up an ActionListener thatchanges the label’s color each timethe button is clicked
20 of 95
JFrame
JLabel
JButtonJPanel
10/9/2014
8
● First, instantiate a newColorTextPanel
● Then, add it to the JFrame bycalling the add method
● Finally, call the method packon the JFrame
o “pack” tells frame to resizeitself based on thepreferred sizes of thecomponents inside it
The ColorTextApp classpublic class ColorTextApp {
public ColorTextApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JPanel panel = new ColorTextPanel();frame.add(panel);frame.pack();
frame.setVisible(true);}
public static void main(String[] args) {new ColorTextApp();
}}
21 of 95
Process1. Create a top-level App class that
contains an instance of JFrame2. Create a subclass of JPanel that
contains an instance of JButton andan instance of JLabel
3. Add an instance of your JPanelsubclass to the JFrame
4. Set up an ActionListener thatchanges the label’s color eachtime the button is clicked
22 of 95
JFrame
JLabel
JButtonJPanel
● Need a way to respond to stimulus of buttonbeing clicked
● We refer to this as event handling
o A source generates an event (like amouse click or a key press) and notifiesall registered listeners
o Each listener has a method forresponding to the event
o stimulus-response mechanism that allowsmultiple listeners to respond
Responding to User Input
23 of 95
● Whenever a JButton is clicked, it generates ajava.awt.event.ActionEvent
● We define class that listens for ActionEvents: mustimplement interface java.awt.event.ActionListener
● ActionListener interface declares method:public void actionPerformed(ActionEvent e);
● This method must be defined in our listener classo called by Java whenever an ActionEvent is firedo specifies response to event
ActionListeners
24 of 95
10/9/2014
9
ActionListeners
Click!
JButton
ActionListener
ActionEvent e
public void actionPerformed( ) {
// Respond here; may or may not use ActionEvent// (print something to the console,// tell a JLabel to change color, etc.)
}
25 of 95
ActionEvent e
Our ActionListener: ColorListener
● Our listener class isColorListener
● Its job is to listen forActionEvents andrespond to them bychanging the color of aJLabel
public class ColorListener implements ActionListener {private JLabel _label; //associated label
public ColorListener(JLabel label) {_label = label; }
@Overridepublic void actionPerformed(ActionEvent e) {
int red = (int) (Math.random()*256);int green = (int) (Math.random()*256);int blue = (int) (Math.random()*256);Color random = new Color(red, green, blue);_label.setForeground(random);
}}
26 of 95
Our ActionListener: ColorListener
● Associated with a JLabel,which it refers to as_label-- a ColorListenerwill be passed the JLabelwhose color it shouldchange
● When ActionEvent isdetected, will change_label’s color
public class ColorListener implements ActionListener {private JLabel _label;
public ColorListener(JLabel label) {_label = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
int red = (int) (Math.random()*256);int green = (int) (Math.random()*256);int blue = (int) (Math.random()*256);Color random = new Color(red, green, blue);_label.setForeground(random);
}}
27 of 95
Our ActionListener: ColorListener
● actionPerformed definesresponse to ActionEvent
● In this case, we want it togenerate a random color,and then set _label to thatcolor
public class ColorListener implements ActionListener {private JLabel _label;
public ColorListener(JLabel label) {_label = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
int red = (int) (Math.random()*256);int green = (int) (Math.random()*256);int blue = (int) (Math.random()*256);Color random = new Color(red, green, blue);_label.setForeground(random);
}}
28 of 95
10/9/2014
10
Our ActionListener: ColorListener
● Use Math.random() togenerate three random ints0-255
● Use them as RGB valuesfor a new Color
● Call JLabel methodsetForeground on _labelto set its color to the randomcolor we’ve created
public class ColorListener implements ActionListener {private JLabel _label;
public ColorListener(JLabel label) {_label = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
int red = (int) (Math.random()*256);int green = (int) (Math.random()*256);int blue = (int) (Math.random()*256);Color random = new Color(red, green, blue);_label.setForeground(random);
}}
29 of 95
Adding ActionListenerspublic class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JButton button = new JButton("Random Color");
ColorListener listener =new ColorListener(label);
button.addActionListener(listener);
Dimension panelSize = new Dimension(150, 75);this.setPreferredSize(panelSize);this.add(label);this.add(button);
}}
30 of 95
● First, instantiate a ColorListener● Pass in label as argument to
listener’s constructor so it knows tochange label’s color
● Next, use methodaddActionListener to add ourColorListener to button
○ Typical pattern: listeners areadded to the event-emittingcomponent they listen to
● Whenever button emits anActionEvent, listener will hear andrespond to it
Process
1. Create a top-level App class thatcontains an instance of JFrame
2. Create a subclass of JFrame thatcontains an instance of JButton andan instance of JLabel
3. Add a JPanel to the JFrame
4. Set up an ActionListener thatchanges the label’s color each timethe button is clicked
31 of 95
JFrame
JLabel
JButtonJPanel
The Whole Apppublic class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JButton button = new JButton("Random Color");ColorListener listener = new ColorListener(label);button.addActionListener(listener);Dimension panelSize = new Dimension(150, 75);this.setPreferredSize(panelSize);this.add(label);this.add(button);
}}
public class ColorListener implements ActionListener {private JLabel _label;
public ColorListener(JLabel label) {_label = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
int red = (int) (Math.random()*256);int green = (int) (Math.random()*256);int blue = (int) (Math.random()*256);Color random = new Color(red, green, blue);_label.setForeground(random);
}}
public class ColorTextApp {
public ColorTextApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
JPanel panel = new ColorTextPanel();frame.add(panel);frame.pack();
frame.setVisible(true);}
public static void main(String[] args) {new ColorTextApp();
}}
32 of 95
10/9/2014
11
Putting It All Together
33 of 95
ColorTextApp
JButton
ColorTextPanel
JLabel ColorListener
JFrame
Logical vs. Graphical Containment
● Graphically, the ColorTextPanel is contained within the JFrame, but logically, both arecontained together in a top-level App class; App and ColorListener aren’t graphic!
● Logical containment is based on where objects are created, while graphical is based on swingelements being added to other swing elements via the add(…) method
● Note: The JButton also has a reference to ColorListener, but this reference is omitted from ourdiagram to avoid excessive complexity.
34 of 95
JFrame
JLabel
JButtonJPanel
ColorTextApp
JButton
ColorTextPanel
JLabel ColorListener
JFrame
Another Swing App: Clock
● Specifications: Appshould display thecurrent date and time,updating every second
● Useful classes: JFrame,JPanel, JLabel, Timer,ActionListener
JFrame
JLabelJPanel
35 of 95
DEMO: Clock
36 of 95
10/9/2014
12
Using Timers● The class javax.swing.Timer comes in handy when we
need to perform a task repeatedly at regular intervals● When we instantiate a Timer, we pass it:
o An int (number of milliseconds between Timer ticks)o An ActionListener that should be notified when the
Timer emits an ActionEvent (on every tick)● We’re going to use a Timer to update the time displayed
on our JLabel at regular intervals37 of 95
Using Timers
Timer
ActionListener
ActionEvent e
Tick!
public void actionPerformed( ) {
// Respond to ActionEvent here!// (print something to the console, tell// a JLabel to update its text, etc.)
}
38 of 95
ActionEvent e
Process: Clock1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanel thatcontains a JLabel. Add aninstance of it to our JFrame
3. Write a class that implementsActionListener-- it should knowabout a JLabel and update itstext on every ActionEvent
4. Instantiate a listener and a Timer,and start the Timer
39 of 95
JFrame
JLabelJPanel
● As in the previousexample, we create a top-level class that contains aJFrame
● Specify closing behavior ofJFrame the same way wedid last time
Top-level Class: Clockpublic class Clock {
public Clock() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new Clock();
}}
40 of 95
10/9/2014
13
● Call pack on the JFrame soit will resize itself based onits contents (which we’ll beadding soon)
● Last, make the frame showup by calling“setVisible(true); ”
Top-level Class: Clockpublic class Clock {
public Clock() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new Clock();
}}
41 of 95
1. Create top-level class thatcontains a JFrame
2. Write a subclass of JPanel thatcontains a JLabel. Add aninstance of it to our JFrame
3. Write a class that implementsActionListener -- it shouldknow about a JLabel and updateits text on every ActionEvent
4. Instantiate a listener and a Timer,and start the Timer
Process: Clock
42 of 95
JFrame
JLabelJPanel
● We’ll call our JPanelsubclass “ClockPanel”
● As in previous example,create a Dimension torepresent desired width andheight of panel
● Call setPreferredSize onpanel, passing in theDimension we created
JPanel subclass: ClockPanel
public class ClockPanel extends JPanel {
public ClockPanel() {Dimension panelSize =
new Dimension(250, 50);this.setPreferredSize(panelSize);
JLabel timeLabel = new JLabel();this.add(timeLabel);
}}
43 of 95
● Instantiate a JLabel, whichwill be used to displaycurrent time
● Add the JLabel to ourpanel
JPanel subclass: ClockPanel
public class ClockPanel extends JPanel {
public ClockPanel() {Dimension panelSize =
new Dimension(250, 50);this.setPreferredSize(panelSize);
JLabel timeLabel = new JLabel();this.add(timeLabel);
}}
44 of 95
10/9/2014
14
● Back in our top-level class● After instantiating our
JFrame, we instantiate aClockPanel and add it tothe frame
Adding a ClockPanel to our JFramepublic class Clock {
public Clock() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
ClockPanel panel = new ClockPanel();frame.add(panel);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new Clock();
}} 45 of 95
Process: Clock1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanel thatcontains a JLabel. Add aninstance of it to our JFrame
3. Write a class that implementsActionListener-- it shouldknow about a JLabel andupdate its text on everyActionEvent
4. Instantiate a listener and a Timer,and start the Timer 46 of 95
JFrame
JLabelJPanel
Our ActionListener: TimerListener
● A TimerListener’s job willbe responding toActionEvents fired by aTimer
● Knows about a particularJLabel, whose text it willmodify with everyActionEvent
public class TimerListenerimplements ActionListener {
private JLabel _timeLabel; //associated label
public TimerListener(JLabel label) {_timeLabel = label; }
@Overridepublic void actionPerformed(ActionEvent e) {
long currTime = System.currentTimeMillis();Date now = new Date(currTime);_timeLabel.setText(now.toString());
}}
47 of 95
Our ActionListener: TimerListener● When ActionEvent fires, we
first determine current dateand time
● System.currentTimeMillisreturns number ofmilliseconds elapsed sincemidnight January 1, 1970
● Can convert this number tothe actual date and time bypassing it into a newjava.util.Date
public class TimerListenerimplements ActionListener {
private JLabel _timeLabel;
public TimerListener(JLabel label) {_timeLabel = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
long currTime = System.currentTimeMillis();Date now = new Date(currTime);_timeLabel.setText(now.toString());
}}
48 of 95
10/9/2014
15
Our ActionListener: TimerListener
● Next, we convert our Dateobject to a String using itstoString method
● We pass the resulting datestring into _timeLabel’ssetText method to update_timeLabel’s text
public class TimerListenerimplements ActionListener {
private JLabel _timeLabel;
public TimerListener(JLabel label) {_timeLabel = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
long currTime = System.currentTimeMillis();Date now = new Date(currTime);_timeLabel.setText(now.toString());
}}
49 of 95
Process: Clock1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanel thatcontains a JLabel. Add aninstance of it to our JFrame
3. Write a class that implementsActionListener-- it should knowabout a JLabel and update itstext on every ActionEvent
4. Instantiate a listener and aTimer, and start the Timer
50 of 95
JFrame
JLabelJPanel
● In constructor ofClockPanel class, weinstantiate a newTimerListener
● Pass in our JLabel,timeLabel, as an argumentso the TimerListener willupdate its text
Instantiating a TimerListenerpublic class ClockPanel extends JPanel {
private Timer _timer;public ClockPanel() {
Dimension panelSize =new Dimension(250, 50);
this.setPreferredSize(panelSize);
JLabel timeLabel = new JLabel();this.add(timeLabel);
TimerListener listener =new TimerListener(timeLabel);
_timer = new Timer(100, listener);_timer.start();
}}
51 of 95
● Next, instantiate a new Timer,and store it in instancevariable _timer
o first argument is number ofms between “ticks”
o second argument is thelistener that will be notifiedon every tick
● Don’t forget to call start onthe Timer!
Instantiating and starting a Timerpublic class ClockPanel extends JPanel {
private Timer _timer;public ClockPanel() {
Dimension panelSize =new Dimension(250, 50);
this.setPreferredSize(panelSize);
JLabel timeLabel = new JLabel();this.add(timeLabel);
TimerListener listener =new TimerListener(timeLabel);
_timer = new Timer(100, listener);_timer.start();
}}
52 of 95
10/9/2014
16
The Whole Apppublic class ClockPanel extends JPanel {
private Timer _timer;public ClockPanel() {
Dimension panelSize = new Dimension(250, 50);this.setPreferredSize(panelSize);
JLabel timeLabel = new JLabel();this.add(timeLabel);
TimerListener listener = new TimerListener(timeLabel);_timer = new Timer(100, listener);_timer.start();
}}public class TimerListener
implements ActionListener {private JLabel _timeLabel;
public TimerListener(JLabel label) {_timeLabel = label;
}
@Overridepublic void actionPerformed(ActionEvent e) {
long currTime = System.currentTimeMillis();Date now = new Date(currTime);_timeLabel.setText(now.toString());
}}
public class Clock {
public Clock() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
ClockPanel panel = new ClockPanel();frame.add(panel);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new Clock();
}}
53 of 95
Putting It All Together: Clock
Clock
JFrame
JLabel TimerTimerListener
ClockPanel
54 of 95
62/102
A Third Swing App: ColorPanelApp
● Specification: An appwith three sliders thatthe user can drag tochange the RGB valuesof the background color
● Useful classes: JFrame,JPanel, JSlider,ChangeListener
JFrame
JSliderJPanel
55 of 95 63/102
DEMO: ColorPanelApp
56 of 95
10/9/2014
17
64/102
● A JSlider lets the user graphically select a value bysliding an arrow within a bounded interval
● One way to construct is by passing two ints (minimumand maximum values) as arguments:
JSlider slider = new JSlider(0, 30);● To get the value of the slider, we can use the getValue
method● A JSlider emits ChangeEvents when value changes--
to listen for them, we use a ChangeListener
Using JSliders
57 of 95 65/102
ChangeListeners ChangeListener
public void stateChanged( ) {
// Respond to ChangeEvent here!// (print something to the console, tell// a JLabel to update its text, etc.)
}
JSlider
ChangeEvent e
ChangeEvent e
58 of 95
66/102
Process: ColorPanelApp1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanel thatcontains three JSliders, add aninstance of it to the JFrame
3. Write a ChangeListener thatchanges a JPanel’s color basedon value of a JSlider
4. Add ChangeListeners to theJSliders
JFrame
JSliderJPanel
59 of 95 67/102
Top-level Class: ColorPanelApp
● This top-level class isalmost identical tothose of the otherexamples-- we followsame pattern of settingup JFrame
● Instantiate JFrame, setits close operation, callpack and setVisible
public class ColorPanelApp {
public ColorPanelApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new ColorPanelApp();
}}
60 of 95
10/9/2014
18
68/102
Process: ColorPanelApp1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanelthat contains three JSliders,add an instance of it to theJFrame
3. Write a ChangeListener thatchanges a JPanel’s color basedon value of a JSlider
4. Add ChangeListeners to theJSliders
JFrame
JSliderJPanel
61 of 95 69/102
JPanel Subclass: ColorPanel
● ColorPanel “is a”JPanel
● As in other examples,create a Dimension,give it desired widthand height, then callsetPreferredSize
● Want panel to start outgray, so call methodsetBackground
public class ColorPanel extends JPanel {
public ColorPanel() {Dimension panelSize = new Dimension(300, 150);this.setPreferredSize(panelSize);this.setBackground(Color.GRAY);JSlider sliderRed = new JSlider(0, 255);JSlider sliderGreen = new JSlider(0, 255);JSlider sliderBlue = new JSlider(0, 255);
this.add(sliderRed);this.add(sliderGreen);this.add(sliderBlue);
}}
62 of 95
70/102
JPanel Subclass: ColorPanel● Instantiate three
JSliders: one tocontrol each channel(red, green, and blue)
● Arguments arebeginning/end ofslider’s range: we giveeach range 0-255 (onebyte/RGB channel)
● Finally, add each sliderto panel
public class ColorPanel extends JPanel {
public ColorPanel() {Dimension panelSize = new Dimension(300, 150);this.setPreferredSize(panelSize);this.setBackground(Color.GRAY);JSlider sliderRed = new JSlider(0, 255);JSlider sliderGreen = new JSlider(0, 255);JSlider sliderBlue = new JSlider(0, 255);
this.add(sliderRed);this.add(sliderGreen);this.add(sliderBlue);
}}
63 of 95 71/102
Adding a ColorPanelApp to the JFrame
● Just as we did inprevious examples,first instantiate a panel,then call add to add itto the JFrame
public class ColorPanelApp {
public ColorPanelApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
ColorPanel panel = new ColorPanel();frame.add(panel);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new ColorPanelApp();
}} 64 of 95
10/9/2014
19
72/102
Process: ColorPanelApp1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanel thatcontains three JSliders, add aninstance of it to the JFrame
3. Write a ChangeListener thatchanges a JPanel’s colorbased on value of a JSlider
4. Add ChangeListeners to theJSliders
JFrame
JSliderJPanel
65 of 95 73/102
Changing a JPanel’s Color● Every JPanel has a pair of accessor and mutator methods,
setBackground and getBackground
● We have three JSliders-- one to control each color channel of theJpanel. Each Jslider has its own listener
● When red slider’s listener detects that its slider has been moved:o it calls getBackground to ask the panel for its current coloro it creates a new instance of Color, using the “R” value from the
slider and the “G” and “B” values from the panel’s currentbackground color (since they haven’t changed)
o it calls setBackground, passing in the new Color66 of 95
74/102
Our ChangeListener: SliderListener● A SliderListener’s job is to
change the color of a JPanelbased on the value of a JSlider
● Since JSliders emitChangeEvents whenever theirvalue changes, SliderListenerimplements ChangeListenerinterface
● Defines method stateChanged.SliderListener will be codedgenerically so it can be used foreach slider
public class SliderListenerimplements ChangeListener {
private JPanel _panel;private int _channel;private JSlider _slider;
public SliderListener(JPanel panel, int channel,JSlider slider){
_panel = panel;_channel = channel;_slider = slider;
}
@Overridepublic void stateChanged(ChangeEvent e) {
// implementation elided for now}
} 67 of 95 75/102
Our ChangeListener: SliderListener● To do its job, it needs to know
three things:
o The JPanel whose colorit should change
o Which channel (red,green, or blue) to modify
o Which slider it listens to
● We’ll represent the channel asan int: 0 means red, 1 meansgreen, 2 means blue
public class SliderListenerimplements ChangeListener {
private JPanel _panel;private int _channel;private JSlider _slider;
public SliderListener(JPanel panel, int channel,JSlider slider){
_panel = panel;_channel = channel;_slider = slider;
}
@Overridepublic void stateChanged(ChangeEvent e) {
// implementation elided for now}
} 68 of 95
10/9/2014
20
76/106
The stateChanged method● Method is called whenever
value of the listener’s JSliderchanges
● Should modify the appropriatecolor channel of the JPanel’sbackground color
● Must take in a ChangeEventas a parameter, because it isrequired by theChangeListener interface;doesn’t use it in this case
// rest of class SliderListener elided for now@Overridepublic void stateChanged(ChangeEvent e) {
int val = _slider.getValue();Color bg = _panel.getBackground();Color newbg;
switch(_channel){case 0:
newbg = new Color(val, bg.getGreen(),bg.getBlue());
break;case 1:
newbg = new Color(bg.getRed(), val,bg.getBlue());
break;default:
newbg = new Color(bg.getRed(), bg.getGreen(),val);
}_panel.setBackground(newbg);
} 69 of 95 77/106
The stateChanged method
● Need to determine new value ofJSlider
● Since we know the source is theJSlider, we can retrieve valueby calling getValue on _slider
// rest of class SliderListener elided for now@Overridepublic void stateChanged(ChangeEvent e) {
int val = _slider.getValue();Color bg = _panel.getBackground();Color newbg;
switch(_channel){case 0:
newbg = new Color(val, bg.getGreen(),bg.getBlue());
break;case 1:
newbg = new Color(bg.getRed(), val,bg.getBlue());
break;default:
newbg = new Color(bg.getRed(), bg.getGreen(),val);
}_panel.setBackground(newbg);
} 70 of 95
78/106
The stateChanged method
● Next, we get the JPanel’scurrent background color
● We declare a new Color, newBg,to which we’ll assign a differentvalue based on which colorchannel the listener is supposedto change
// rest of class SliderListener elided for now@Overridepublic void stateChanged(ChangeEvent e) {
int val = _slider.getValue();Color bg = _panel.getBackground();Color newbg;
switch(_channel){case 0:
newbg = new Color(val, bg.getGreen(),bg.getBlue());
break;case 1:
newbg = new Color(bg.getRed(), val,bg.getBlue());
break;default:
newbg = new Color(bg.getRed(), bg.getGreen(),val);
}_panel.setBackground(newbg);
} 71 of 95 79/106
The stateChanged method
● Depending on the value of_channel, we set newBg to adifferent color
● In each case, only the specifiedcolor channel changes; we usethe gets for the values of theunchanged channels
● Once we’ve changed theappropriate channel, we set theJPanel’s background color tonewBg
// rest of class SliderListener elided for now@Overridepublic void stateChanged(ChangeEvent e) {
int val = _slider.getValue();Color bg = _panel.getBackground();Color newbg;
switch(_channel){case 0:
newbg = new Color(val, bg.getGreen(),bg.getBlue());
break;case 1:
newbg = new Color(bg.getRed(), val,bg.getBlue());
break;default:
newbg = new Color(bg.getRed(), bg.getGreen(),val);
}_panel.setBackground(newbg);
} 72 of 95
10/9/2014
21
80/106
Process: ColorPanelApp1. Create top-level class that
contains a JFrame
2. Write a subclass of JPanel thatcontains three JSliders, add aninstance of it to the JFrame
3. Write a ChangeListener thatchanges a JPanel’s color basedon value of a JSlider
4. Add ChangeListeners to theJSliders
JFrame
JSliderJPanel
73 of 95 81/106
Setting up our SliderListeners● Back in ColorPanel
class● Call method
addChangeListener oneach slider, passing in anew instance ofSliderListener
● Pass in ColorPanel,appropriate channelnumber and slider asarguments to eachSliderListener
public class ColorPanel extends JPanel {
public ColorPanel() {Dimension panelSize = new Dimension(300, 150);this.setPreferredSize(panelSize);this.setBackground(Color.GRAY);JSlider sliderRed = new JSlider(0, 255);JSlider sliderGreen = new JSlider(0, 255);JSlider sliderBlue = new JSlider(0, 255);sliderRed.addChangeListener(
new SliderListener(this, 0, sliderRed));sliderGreen.addChangeListener(
new SliderListener(this, 1, sliderGreen));sliderBlue.addChangeListener(
new SliderListener(this, 2, sliderBlue));this.add(sliderRed);this.add(sliderGreen);this.add(sliderBlue);
}} 74 of 95
82/106
The Whole App (1/2)public class ColorPanel extends JPanel {
public ColorPanel() {Dimension panelSize = new Dimension(300, 150);this.setPreferredSize(panelSize);this.setBackground(Color.GRAY);JSlider sliderRed = new JSlider(0, 255);JSlider sliderGreen = new JSlider(0, 255);JSlider sliderBlue = new JSlider(0, 255);
sliderRed.addChangeListener(new SliderListener(this, 0, sliderRed));
sliderGreen.addChangeListener(new SliderListener(this, 1, sliderGreen));
sliderBlue.addChangeListener(new SliderListener(this, 2, sliderBlue));
this.add(sliderRed);this.add(sliderGreen);this.add(sliderBlue);
}}
public class ColorPanelApp {
public ColorPanelApp() {JFrame frame = new JFrame();frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
ColorPanel panel = new ColorPanel();frame.add(panel);
frame.pack();frame.setVisible(true);
}
public static void main(String[] args) {new ColorPanelApp();
}}
75 of 95 83/106
The Whole App (2/2)
public class SliderListenerimplements ChangeListener {
private JPanel _panel;private int _channel;
public SliderListener(JPanel panel, int channel){_panel = panel;_channel = channel;
}
@Overridepublic void stateChanged(ChangeEvent e) {
int val = _slider.getValue();Color bg = _panel.getBackground();Color newbg;switch(_channel){case 0:
newbg = new Color(val, bg.getGreen(),bg.getBlue());
break;case 1:
newbg = new Color(bg.getRed(), val,bg.getBlue());
break;default:
newbg = new Color(bg.getRed(), bg.getGreen(),val);
}_panel.setBackground(newbg); }
}
76 of 95
10/9/2014
22
84/106
Putting It All Together: ColorPanelApp
ColorPanelApp
JFrame ColorPanel
JSlider SliderListener
77 of 95 85/106
Buttons in Swing
Some buttons in Swing:● javax.swing.JButton● javax.swing.JToggleButton● javax.swing.JCheckBox● javax.swing.JRadioButton
78 of 95
86/106
Buttons in Swing
79 of 95 87/106
ButtonGroups
● How do we make options mutually exclusive(i.e. you can only click one button at a time)?o put them in a button groupo javax.swing.ButtonGroup
● Buttons that can be added to ButtonGroup:JRadioButtonJToggleButtonJMenuItem (for advanced users)
80 of 95
10/9/2014
23
88/106
JRadioButtons & ButtonGroups
● How to use a ButtonGroup:o create buttons
JRadioButton rB1 = new JRadioButton(“Green, not Red”);JRadioButton rB2 = new JRadioButton(“Red, not Green”);
o create ButtonGroupButtonGroup bGroup = new ButtonGroup();
o add buttons to ButtonGroupbGroup.add(rB1);bGroup.add(rB2);
81 of 95 89/106
public class RadioColorListener implements ActionListener {private JLabel _label;private Color _currentColorpublic RadioColorListener(JLabel label, Color color) {
_label = label;_currentColor = color;
}@Overridepublic void actionPerformed(ActionEvent e) {
_label.setForeground(_currentColor);}
}
Modified ColorTextApp: RadioColorListener
82 of 95
90/106
Modified ColorTextApp: ColorTextPanelpublic class ColorTextPanel extends JPanel {
public ColorTextPanel() {JLabel label = new JLabel("CS15 Rocks!");JRadioButton buttonForRed = new JRadioButton("Red");JRadioButton buttonForGreen = new JRadioButton(“Green);RadioColorListener redListener = new RadioColorListener(label, Color.RED);RadioColorListener greenListener = new RadioColorListener(label, Color.GREEN);
//add listeners to their buttonsbuttonForRed.addActionListener(redListener);buttonForGreen.addActionListener(greenListener);
//create button group and add buttons to itButtonGroup buttonGroup = new ButtonGroup();buttonGroup.add(buttonForRed);buttonGroup.add(buttonForGreen);Dimension panelSize = new Dimension(300, 100);this.setPreferredSize(panelSize);
//add label and buttons to ColorTextPanelthis.add(label);this.add(buttonForRed);this.add(buttonForGreen);
}}
Assume all the swingcomponents areimported!
For more complex projectsyou might want to give theButtons a separate JPaneland use LayoutManagers(stay tuned!)
83 of 95 91/106
More Complicated Swing Apps
● The examples we’ve seen so far have been small andsimple
● What if we want to construct a more realistic GUI?● We can use LayoutManagers to arrange components
nicely within JPanels
84 of 95
10/9/2014
24
92/106
Using java.awt.LayoutManagers● Each JPanel contains a LayoutManager to
automatically arrange its sub-components● LayoutManager interface implemented by classes:
o java.awt.FlowLayouto java.awt.GridLayouto java.awt.BorderLayout
● To specify the LayoutManager for a JPanel, eitherpass an instance of one of these classes to the panel’sconstructor or to its setLayout method later 85 of 95 93/106
FlowLayout
● Default layout used byall JPanels
● Arranges componentsfrom left to right, top tobottom
● When it reaches theedge of the panel,moves to next row
86 of 95
94/106
public class FlowTest extends JFrame {
public FlowTest() {super();this.setSize(200, 300);JButton b1 = new JButton(“One”);JButton b2 = new JButton(“Two”);JButton b3 = new JButton(“Tree”);JButton b4 = new JButton(“Four”);JButton b5 = new JButton(“Five”);JButton b6 = new JButton(“Six”);JPanel mainPanel = new JPanel();
FlowLayout fl = new Flowlayout();mainPanel.setLayout(fl);mainPanel.add(b1);mainPanel.add(b2);mainPanel.add(b3);mainPanel.add(b4);mainPanel.add(b5);mainPanel.add(b6);this.add(mainPanel);this.pack();this.setVisible(true);
}}
FlowLayout
87 of 95 95/106
GridLayout● Arranges components in
a grid● Add components left to
right, top to bottom● Must specify grid size in
constructor-- number ofrows and columns
● Each cell in grid is samesize, determined bylargest element in grid 95 of 95
10/9/2014
25
96/106
public class GridTest extends JFrame {
public GridTest() {super();this.setSize(200, 300);JPanel p1 = new JPanel();JPanel p2 = new JPanel();JPanel p3 = new JPanel();JPanel p4 = new JPanel();JPanel p5 = new JPanel();JPanel p6 = new JPanel();JPanel mainPanel = new JPanel();
p1.setBackground(Color.GREEN);p2.setBackground(Color.RED);p3.setBackground(Color.ORANGE);p4.setBackground(Color.CYAN);p5.setBackground(Color.BLUE);p6.setBackground(Color.YELLOW);
GridLayout gl = new GridLayout(3, 2);mainPanel.setLayout(gl);mainPanel.add(p1);mainPanel.add(p2);mainPanel.add(p3);mainPanel.add(p4);mainPanel.add(p5);mainPanel.add(p6);this.add(mainPanel);this.pack();this.setVisible(true);
}}
GridLayout
89 of 95 97/106
BorderLayout
● Splits JPanel into 5regions: NORTH, SOUTH,EAST, WEST, CENTERo These are all static
constants● Must specify region when
adding component to itscontainer
90 of 95
98/106
BorderLayout
● Don’t have to fill allregions-- default size of aregion is (0, 0)
● BorderLayout will adjustdynamically dependingon what has been added
● Typically add to CENTERfirst-- it should be largest
91 of 95 99/106
BorderLayoutpublic class BorderTest extends JFrame {
public BorderTest() {super();this.setSize(300, 200);JPanel p1 = new JPanel();JPanel p2 = new JPanel();JPanel p3 = new JPanel();JPanel p4 = new JPanel();JPanel p5 = new JPanel();JPanel mainPanel = new JPanel();
p1.setBackground(Color.RED);p2.setBackground(Color.GREEN);p3.setBackground(Color.ORANGE);p4.setBackground(Color.CYAN);p5.setBackground(Color.BLUE);
BorderLayout bl = new BorderLayout();mainPanel.setLayout(bl);mainPanel.add(p1, BorderLayout.CENTER);mainPanel.add(p2, BorderLayout.NORTH);mainPanel.add(p3, BorderLayout.SOUTH);mainPanel.add(p4, BorderLayout.EAST);mainPanel.add(p5, BorderLayout.WEST);this.add(mainPanel);this.pack();this.setVisible(true);
}} 92 of 95
10/9/2014
26
100/106
LayoutManagers● You’ll be using layouts a lot in
CS15-- practice playing aroundwith them!
● Try taking the previous exampleand calling setPreferredSizeon each sub-panel to changetheir sizes and shapes
● If you want to test yourunderstanding (and want to geta headstart on Cartoon), trymaking something like this:
93 of 95 101/106
LayoutManagers
94 of 95
102/106
Swing: Summary● Swing has a variety of tools to help you make
GUIs:o JFrames, JPanels, JButtons, and JSliders, arranged using
LayoutManagerso ActionListeners and ChangeListeners to respond to user inputo Timers to perform a task at regular intervals
● On future projects, instead of relying on supportcode for graphical elements, you will use thesetools yourself!
95 of 95
Announcements● On-time Due Date for TASafeHouse is Friday,
October 3rd, at 10:00 PM
● Late Due Date for TASafeHouse is Sunday,October 5th, at 11:59 PM
Top Related