Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques Assignment 5: Will be an open-ended Swing project. "Programming Contest" last day of classes (if time permits) 1 2 Outline A. Basics a little background & history putting a frame (window) on the screen GUIs Up to now: line-by-line programs: computer displays text user types text 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 GUI = Graphical User Interface Advantages & disadvantages? D. Graphics using icons drawing custom pictures 3 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 Swing Extension to AWT: part of Java API in versions 1.2 & later some new features (file & color choosers, more graphics features) X-Windows for Unix/Linux Microsoft Foundation Classes (MFC) for Windows etc. not portable replaced some items with improved versions (Button -> JButton, Frame -> JFrame all start with "J") some improvements to existing features (double buffering) 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) Still use parts of AWT that Swing hasn't replaced: same old layout managers, basic graphics commands 5 6 Packages For a basic Java GUI program, import these packages: import javax.swing.*; import java.awt.*; import java.awt.event.*; 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 7 8
Getting a Window Running Fonts 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") A font consists of: name ("Serif", "Sanserif", "Monospaced") type (constants: PLAIN, ITALIC, BOLD) size (in points) First set of demos: "baby Swing" Example: Font bigfont = new Font("Serif", Font.PLAIN, 24); quitbutton.setfont(bigfont); 9 10 Colours JOptionPane (1) class Color: constants for common colours (RED, BLUE, BLACK, etc.) constructor to create a custom colour: Color(int r, int g, int b) JOptionPane class for common pop-up windows many capabilities; we'll look at 3 basic static methods JOptionPane.showMessageDialog(myFrame, "hello, world!"); 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 12
JOptionPane (2) JOptionPane (3) int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?"); String name = JOptionPane.showInputDialog(myFrame, "what is your name?"); result gets one of three values: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION name gets user input -- or null if user clicks "Cancel" 13 14 Outline 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" Layout Managers layout manager decides: position of each component in frame size of each component what changes when window is resized C. Components & Actions more kinds of components adding actions to components programmer's job: give layout manager some general instructions NOT exact positions and sizes D. Graphics using icons drawing custom pictures 15 16
Different Kinds of Layout Managers We will concentrate on three: BorderLayout FlowLayout GridLayout 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" Each has different purpose, different layout algorithms. Real power comes from combining them -- different parts of frame. Button at preferred size: Same button, stretched: 17 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 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 19 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 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. 21 22 Combining Layouts Panel Example 1 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" Suppose we want to put 6 buttons in a frame like this: 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 24
Panel Example 2 Panel Example 3 Suppose we want to put 6 buttons in a frame like this: Suppose we want to put 6 buttons in a frame like this (small change from example 2): 25 26 More Complicated Example 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 27 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) Goal For This Sub-Topic A simple program using three kinds of components with actions attached demo... Plus how to use "listeners" to attach actions to components 29 30 JButton JButton Methods "clickable" button with a border String gettext() void settext(string newtext) void setenabled(boolean enabled); default is true disabled button is "greyed out", no graphic reaction when clicked JButton addbutton = new JButton("add"); 31 32
JLabel Puts text on screen No borders, no actions, no background color (transparent) JLabel Methods String gettext() void settext(string newtext) JLabel addlabel = new JLabel("amount to add: "); 33 34 two kinds: text field (one line) text area (multiple lines) Text Components one line only space for entering/displaying text JTextField "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); 35 36
JTextArea like a JTextField, but multiple lines Methods For Text Components String gettext() void settext(string newtext) JTextArea quotetextarea = new JTextArea(3,20); JTextArea databasearea = new JTextArea(20, 30); databasearea.seteditable(false); 37 38 Event-Driven Programming ActionEvent Class 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 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 39 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 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 41 42 Demo: Baby Calculator Three different styles: inner listener class(es) use frame as listener anonymous inner classes 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 43 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 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 D. Graphics using icons drawing custom pictures 45 46 paintcomponent (1) paintcomponent (2) every component has a paintcomponent method default method: draws text, borders, etc. on screen you can override to create your own graphics effects 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 47 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! Note About Coordinates Swing uses x & y coordinates, different from math x positive x: to the right positive y: down y 49 50 Simple Example Program paintcomponent vs. repaint start with a static display; add actions 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 51 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