1 CISC 124, Winter 2016, topic 9: Swing Topic 9: Swing Swing is a BIG library Goal: • cover basics • give you concepts & tools for learning more Swing = Java's GUI library Assignment 5: Will be an open-ended Swing project. "Programming Contest" last day of classes (if time permits) Swing = Java's GUI library Swing = Java's GUI library
53
Embed
Topic 9: Swingcourses.caslab.queensu.ca/cisc124/wp-content/... · • replaced some items with improved versions (Button -> JButton, Frame -> JFrame – all start with "J") • some
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1CISC 124, Winter 2016, topic 9: Swing
Topic 9: Swing
Swing is a BIG libraryGoal:
• cover basics• give you concepts & tools for learning more
Swing = Java's GUI library
Assignment 5: Will be an open-ended Swing project."Programming Contest" last day of classes (if time permits)
int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?");
result gets one of three values:JOptionPane.YES_OPTIONJOptionPane.NO_OPTIONJOptionPane.CANCEL_OPTION
14CISC 124, Winter 2016, topic 9: Swing
JOptionPane (3)
String name = JOptionPane.showInputDialog(myFrame, "what is your name?");
name gets user input -- or null if user clicks "Cancel"
15CISC 124, Winter 2016, topic 9: Swing
A. Basicsa little background & historyputting a frame (window) on the screen
B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"
C. Components & Actionsmore kinds of componentsadding actions to components
Outline�
D. Graphicsusing iconsdrawing custom pictures
16CISC 124, Winter 2016, topic 9: Swing
Layout Managerslayout manager decides:
● position of each component in frame● size of each component● what changes when window is resized
programmer's job: give layout manager some general instructions
NOT exact positions and sizes
17CISC 124, Winter 2016, topic 9: Swing
Different Kinds of Layout ManagersWe will concentrate on three:
● BorderLayout● FlowLayout● GridLayout
Each has different purpose, different layout algorithms.Real power comes from combining them -- different parts of frame.
18CISC 124, Winter 2016, topic 9: Swing
Sizes of ComponentsEvery component has a "preferred size"For buttons and labels, based on the text and the fontSometimes layout managers "stretch" components beyond the "preferred size"
Button at preferred size: Same button, stretched:
19CISC 124, Winter 2016, topic 9: Swing
BorderLayoutdefault layout manager for framesframe has 5 positions:NORTH, SOUTH, EAST, WEST, CENTER
demo....
Rules:• max of 1 component in each position• OK to have some positions empty• north & south stretched horizontally to fit frame• east & west stretched vertically• center stretched both ways• can specify gaps
20CISC 124, Winter 2016, topic 9: Swing
FlowLayoutadds components left to rightdemo....
Rules:• components always at preferred sizes – never stretches components• breaks into multiple rows if necessary• can specify alignment & gaps
FAQ: can you create a vertical row with a FlowLayout?Answer: no
21CISC 124, Winter 2016, topic 9: Swing
GridLayoutlays out components in a rectangular griddemo...
Rules:• components are stretched to fill frame• all components have same dimensions• specify number of rows OR number of columns• can specify gaps
22CISC 124, Winter 2016, topic 9: Swing
Changing a Preferred SizeYou may state a preference about the size of a component:
btn.setPreferredSize(new Dimension(120,45));
This does *not* guarantee that the button will be the size you asked for!
Combining LayoutsNow we know about 3 kinds of layoutsEach fairly limited by itselfCan sub-divide frame into sections, lay each out individuallyeach section called a "panel"
Swing class: JPanel
a component which is also a containercan add other components to a JPanel
to create:new JPanel(new GridLayout(2,0));
new JPanel(); // default is FlowLayout
24CISC 124, Winter 2016, topic 9: Swing
Panel Example 1Suppose we want to put 6 buttons in a frame like this:
25CISC 124, Winter 2016, topic 9: Swing
Panel Example 2Suppose we want to put 6 buttons in a frame like this:
26CISC 124, Winter 2016, topic 9: Swing
Panel Example 3Suppose we want to put 6 buttons in a frame like this
(small change from example 2):
27CISC 124, Winter 2016, topic 9: Swing
More Complicated Example
28CISC 124, Winter 2016, topic 9: Swing
A. Basicsa little background & historyputting a frame (window) on the screen
B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"
C. Components & Actionsmore kinds of componentsadding actions to components
Outline�
D. Graphicsusing iconsdrawing custom pictures
�
29CISC 124, Winter 2016, topic 9: Swing
We will talk about 4 different kinds of components:● buttons● labels● text fields● text areas (optional – will not be tested)
Part C: Components & Actions
Plus how to use "listeners" to attach actions to components
30CISC 124, Winter 2016, topic 9: Swing
Goal For This Sub-TopicA simple program using three kinds of components with actions
attacheddemo...
31CISC 124, Winter 2016, topic 9: Swing
JButton"clickable" button with a border
JButton addButton = new JButton("add");
32CISC 124, Winter 2016, topic 9: Swing
JButton MethodsString getText()
void setText(String newText)
void setEnabled(boolean enabled);
• default is true• disabled button is "greyed out", no graphic reaction when clicked
33CISC 124, Winter 2016, topic 9: Swing
JLabelPuts text on screenNo borders, no actions, no background color (transparent)
JLabel addLabel =
new JLabel("amount to add: ");
34CISC 124, Winter 2016, topic 9: Swing
JLabel MethodsString getText()
void setText(String newText)
35CISC 124, Winter 2016, topic 9: Swing
Text Componentstwo kinds:
text field (one line)text area (multiple lines)
36CISC 124, Winter 2016, topic 9: Swing
JTextFieldone line onlyspace for entering/displaying text
"editable"
not "editable"
JTextField addField = new JTextField(10);
JTextField multField = new JTextField(10);
JTextField totalField = new JTextField(10);
totalField.setEditable(false);
width in "m spaces"
37CISC 124, Winter 2016, topic 9: Swing
JTextArealike a JTextField, but multiple lines
JTextArea databaseArea = new JTextArea(20, 30);
databaseArea.setEditable(false);
JTextArea quoteTextArea = new JTextArea(3,20);
38CISC 124, Winter 2016, topic 9: Swing
Methods For Text ComponentsString getText()
void setText(String newText)
39CISC 124, Winter 2016, topic 9: Swing
Event-Driven ProgrammingImperative Programming:
You specify sequence of commandsProgrammer in control
Event-Driven Programming:sequence driven by user's choicesprogram waits for "events" and reacts to them
Examples of events:• button click• menu choice• window closed or resized• mouse clicks, mouse motion
40CISC 124, Winter 2016, topic 9: Swing
ActionEvent Classdescribes a simple event like a button click, menu choicemethods:
Object getSource()returns the component that "caused" the event
(button that was clicked)
String getActionCommand()returns text from component
Program can register an action listener for a button.Meaning: when button is clicked, call actionPerformed in this listener
42CISC 124, Winter 2016, topic 9: Swing
Sequence of EventsSet-up (usually in constructor):• create button• create listener• register listener with button
During Program Run:1. user clicks button2. Swing checks whether button has a listener3. if yes:
Swing creates an ActionEvent objectSwing calls actionPerformed method in listener with the
object as argument
you write this code
Swing does this for you
43CISC 124, Winter 2016, topic 9: Swing
Demo: Baby CalculatorThree different styles:
• inner listener class(es)
• use frame as listener
• anonymous inner classes
44CISC 124, Winter 2016, topic 9: Swing
A. Basicsa little background & historyputting a frame (window) on the screen
B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"
C. Components & Actionsmore kinds of componentsadding actions to components
D. Graphicsusing iconsdrawing custom pictures
Outline�
�
�
45CISC 124, Winter 2016, topic 9: Swing
A. Basicsa little background & historyputting a frame (window) on the screen
B. Layoutsarranging multiple components in a framethree different kinds of "layout managers"
C. Components & Actionsmore kinds of componentsadding actions to components
Outline�
D. Graphicsusing iconsdrawing custom pictures
�
�
46CISC 124, Winter 2016, topic 9: Swing
We've seen how to put text on componentsAlso possible to put "icon" (image from file) onto component.
Part D: Graphics
Sometimes we want to draw our own pictures dynamicallyOften use an empty panel
47CISC 124, Winter 2016, topic 9: Swing
paintComponent (1)every component has a paintComponent method
default method: draws text, borders, etc. on screenyou can override to create your own graphics effects
48CISC 124, Winter 2016, topic 9: Swing
paintComponent (2)void paintComponent(Graphics g)
Parameter: "graphics context"• current drawing colour & font• position & size of component• lots more
You never call paintComponent!
Swing calls it automatically whenever the component needs painting:• frame is created• frame is resized• frame is minimized then restored
49CISC 124, Winter 2016, topic 9: Swing
Graphics methodsvoid drawLine(int x1, int y1, int x2, int y2)
void drawString(String str, int x, int y)
void drawRect(int x, int y, int width,
int height)
void fillRect(int x, int y, int width,
int height)
void drawOval(int x, int y, int width,
int height)
void fillOval(int x, int y, int width,
int height)
...and lots more!
50CISC 124, Winter 2016, topic 9: Swing
Note About CoordinatesSwing uses x & y coordinates, different from math
x
y
positive x: to the right
positive y: down
51CISC 124, Winter 2016, topic 9: Swing
Simple Example Programstart with a static display; add actions
52CISC 124, Winter 2016, topic 9: Swing
paintComponent vs. repaintpaintComponent:
• takes a Graphics object as a parameter• you override paintComponent to draw your picture• Swing (not you!) calls paintComponent when necessary
repaint:• no parameters• you call it to tell Java the component's graphics need to be
updated• you don't write or override it• defined by Swing: gets the appropriate Graphics context and
calls paintComponent
53CISC 124, Winter 2016, topic 9: Swing
SummaryFor custom graphic effects:
• "state variables" to store information about current state of graphics
•button clicks & other actions change those variables•create custom component subclass for drawing•subclass gets special paintComponent method which uses the state variables
•remember to call repaint() when you change the state variables!