Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest" last day of classes (if time permits) 1
Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques 2
A. Basics a little background & history putting a frame (window) on the screen B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures Outline 3
GUIs Up to now: line-by-line programs: computer displays text user types text GUI = Graphical User Interface Advantages & disadvantages? 4
AWT Early GUIs: write your own, huge amount of work Common style emerged: mouse, buttons, text boxes, menus Libraries to help you write GUI programs X-Windows for Unix/Linux Microsoft Foundation Classes (MFC) for Windows etc. not portable AWT = Abstract Window Toolkit part of Java API classes for writing portable GUI programs easier to use than MFC can be used by itself (no Swing) 5
Swing Extension to AWT: part of Java API in versions 1.2 & later some new features (file & color choosers, more graphics features) replaced some items with improved versions (Button -> JButton, Frame -> JFrame all start with "J") some improvements to existing features (double buffering) Still use parts of AWT that Swing hasn't replaced: same old layout managers, basic graphics commands 6
Packages For a basic Java GUI program, import these packages: import javax.swing.*; import java.awt.*; import java.awt.event.*; 7
Tasks in GUI Programming 1. Getting your screen to look the way you want it to. (laying out components buttons, text boxes, etc.) 2. Getting the program to do what you want it to. (functionality) These tasks are somewhat independent. Common order: 1. get screen looking right, no functionality 2. add functionality Another possibility: 1. put components on screen, quick & sloppy 2. add functionality, debug 3. improve appearance 8
Getting a Window Running First practical task: get a window up on your screen and be able to exit gracefully Basic Swing class: JFrame A frame is a window with: a border a title menu bar (optional place to put menu items) minimize, maximize, close buttons inner area for contents ("content pane") First set of demos: "baby Swing" 9
Fonts A font consists of: name ("Serif", "Sanserif", "Monospaced") type (constants: PLAIN, ITALIC, BOLD) size (in points) Example: Font bigfont = new Font("Serif", Font.PLAIN, 24); quitbutton.setfont(bigfont); 10
class Color: Colours constants for common colours (RED, BLUE, BLACK, etc.) constructor to create a custom colour: Color(int r, int g, int b) methods in JComponent: setbackground(color c) setforeground(color c) Notes: some components don't use both colours labels are transparent (no background colour) panels have no foreground colour 11
JOptionPane (1) JOptionPane class for common pop-up windows many capabilities; we'll look at 3 basic static methods JOptionPane.showMessageDialog(myFrame, "hello, world!"); 12
JOptionPane (2) int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?"); result gets one of three values: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION 13
JOptionPane (3) String name = JOptionPane.showInputDialog(myFrame, "what is your name?"); name gets user input -- or null if user clicks "Cancel" 14
A. Basics a little background & history putting a frame (window) on the screen B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures Outline 15
Layout Managers layout 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 16
Different Kinds of Layout Managers We will concentrate on three: BorderLayout FlowLayout GridLayout Each has different purpose, different layout algorithms. Real power comes from combining them -- different parts of frame. 17
Sizes of Components Every component has a "preferred size" For buttons and labels, based on the text and the font Sometimes layout managers "stretch" components beyond the "preferred size" Button at preferred size: Same button, stretched: 18
BorderLayout default layout manager for frames frame 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 19
adds components left to right demo... FlowLayout 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 20
GridLayout lays out components in a rectangular grid demo... Rules: components are stretched to fill frame all components have same dimensions specify number of rows OR number of columns can specify gaps 21
Changing a Preferred Size You may state a preference about the size of a component: btn.setpreferredsize(new Dimension(120,45)); You may also query the preferred size: Dimension size3 = btn.getpreferredsize(); btn.setpreferredsize( new Dimension(size3.width*2,size3.height)); This does *not* guarantee that the button will be the size you asked for! The layout manager is still in charge. 22
Combining Layouts Now we know about 3 kinds of layouts Each fairly limited by itself Can sub-divide frame into sections, lay each out individually each section called a "panel" Swing class: JPanel a component which is also a container can add other components to a JPanel to create: new JPanel(new GridLayout(2,0)); new JPanel(); // default is FlowLayout 23
Panel Example 1 Suppose we want to put 6 buttons in a frame like this: 24
Panel Example 2 Suppose we want to put 6 buttons in a frame like this: 25
Panel Example 3 Suppose we want to put 6 buttons in a frame like this (small change from example 2): 26
More Complicated Example 27
A. Basics a little background & history putting a frame (window) on the screen Outline B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures 28
Part C: Components & Actions We will talk about 4 different kinds of components: buttons labels text fields text areas (optional will not be tested) Plus how to use "listeners" to attach actions to components 29
Goal For This Sub-Topic A simple program using three kinds of components with actions attached demo... 30
"clickable" button with a border JButton JButton addbutton = new JButton("add"); 31
JButton Methods String gettext() void settext(string newtext) void setenabled(boolean enabled); default is true disabled button is "greyed out", no graphic reaction when clicked 32
JLabel Puts text on screen No borders, no actions, no background color (transparent) JLabel addlabel = new JLabel("amount to add: "); 33
JLabel Methods String gettext() void settext(string newtext) 34
two kinds: text field (one line) text area (multiple lines) Text Components 35
JTextField one line only space for entering/displaying text "editable" not "editable" JTextField addfield = new JTextField(10); width in "m spaces" JTextField multfield = new JTextField(10); JTextField totalfield = new JTextField(10); totalfield.seteditable(false); 36
JTextArea like a JTextField, but multiple lines JTextArea quotetextarea = new JTextArea(3,20); JTextArea databasearea = new JTextArea(20, 30); databasearea.seteditable(false); 37
Methods For Text Components String gettext() void settext(string newtext) 38
Event-Driven Programming Imperative Programming: You specify sequence of commands Programmer in control Event-Driven Programming: sequence driven by user's choices program waits for "events" and reacts to them Examples of events: button click menu choice window closed or resized mouse clicks, mouse motion 39
ActionEvent Class describes a simple event like a button click, menu choice methods: Object getsource() returns the component that "caused" the event (button that was clicked) String getactioncommand() returns text from component 40
ActionListener Interface public interface ActionListener { void actionperformed(actionevent e); } Program can register an action listener for a button. Meaning: when button is clicked, call actionperformed in this listener 41
Sequence of Events Set-up (usually in constructor): create button create listener register listener with button you write this code During Program Run: Swing does this for you 1. user clicks button 2. Swing checks whether button has a listener 3. if yes: Swing creates an ActionEvent object Swing calls actionperformed method in listener with the object as argument 42
Demo: Baby Calculator Three different styles: inner listener class(es) use frame as listener anonymous inner classes 43
A. Basics a little background & history putting a frame (window) on the screen B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures Outline 44
A. Basics a little background & history putting a frame (window) on the screen Outline B. Layouts arranging multiple components in a frame three different kinds of "layout managers" C. Components & Actions more kinds of components adding actions to components D. Graphics using icons drawing custom pictures 45
Part D: Graphics We've seen how to put text on components Also possible to put "icon" (image from file) onto component. Sometimes we want to draw our own pictures dynamically Often use an empty panel 46
paintcomponent (1) every component has a paintcomponent method default method: draws text, borders, etc. on screen you can override to create your own graphics effects 47
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 48
Graphics methods void 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! 49
Note About Coordinates Swing uses x & y coordinates, different from math x positive x: to the right positive y: down y 50
Simple Example Program start with a static display; add actions 51
paintcomponent vs. repaint paintcomponent: 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 52
Summary For 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! 53