Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming Contest" last day of classes: A. Basics today 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 drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 1 2 GUIs Up to now: line-by-line programs: computer displays text user types text AWT Early GUIs: write your own, huge amount of work Common style emerged: buttons, text boxes, menus Libraries to help you write GUI programs GUI = Graphical User Interface Advantages & disadvantages? 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) 3 4
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) Packages For a basic Java GUI program, import these packages: import javax.swing.*; import java.awt.*; import java.awt.event.*; Still use parts of AWT that Swing hasn't replaced: same old layout managers, basic graphics commands 5 6 Tasks in GUI Programming Getting a Window Running 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 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") Another possibility: 1. put components on screen, quick & sloppy 2. add functionality, debug 3. improve appearance 7 8
Fonts A font consists of: name ("Serif", "Sanserif", "Monospaced") type (constants: PLAIN, ITALIC, BOLD) size (in points) Colours class Color: 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) Example: Font bigfont = new Font("Serif", Font.PLAIN, 24); quitbutton.setfont(bigfont); Notes: some components don't use both colours labels are transparent (no background colour) panels have no foreground colour 9 10 JOptionPane (1) JOptionPane (2) JOptionPane class for common pop-up windows many capabilities; we'll look at 3 basic static methods int result = JOptionPane.showConfirmDialog(myFrame, "are you awake?"); JOptionPane.showMessageDialog(myFrame, "hello, world!"); result gets one of three values: JOptionPane.YES_OPTION JOptionPane.NO_OPTION JOptionPane.CANCEL_OPTION 11 12
JOptionPane (3) String name = JOptionPane.showInputDialog(myFrame, "what is your name?"); 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" C. Components & Actions more kinds of components adding actions to components name gets user input -- or null if user clicks "Cancel" D. Graphics drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 13 14 Layout Managers Different Kinds of Layout Managers layout manager decides: position of each component in frame size of each component what changes when window is resized We will concentrate on three: BorderLayout FlowLayout GridLayout programmer's job: give layout manager some general instructions Each has different purpose, different layout algorithms. Real power comes from combining them -- different parts of frame. 15 16
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 BorderLayout default layout manager for frames frame has 5 positions: NORTH, SOUTH, EAST, WEST, CENTER demo... Button at preferred size: Same button, stretched: Rules: max of 1 component in each position north & south stretched horizontally to fit frame east & west stretched vertically center stretched both ways can specify gaps 17 18 FlowLayout GridLayout adds components left to right demo... lays out components in a rectangular grid demo... Rules: components always at preferred sizes breaks into multiple rows if necessary can specify alignment & gaps Rules: components are stretched to fill frame all components have same dimensions specify number of rows OR number of columns can specify gaps FAQ: can you create a vertical row with a FlowLayout? no! 19 20
Changing a Preferred Size Combining Layouts You may state a preference about the size of a component: btn.setpreferredsize(new Dimension(120,45)); You may also query the preferred size: 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" 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. 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 21 22 Panel Example 1 Panel Example 2 Suppose we want to put 6 buttons in a frame like this: Suppose we want to put 6 buttons in a frame like this: 23 24
Panel Example 3 More Complicated Example Suppose we want to put 6 buttons in a frame like this (small change from example 2): 25 26 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 Outline Part C: Components & Actions We will talk about 4 different kinds of components: buttons labels text fields text areas Plus how to use "listeners" to attach actions to components D. Graphics drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 27 28
Goal For This Sub-Topic A simple program using three kinds of components with actions attached demo... "clickable" button with a border JButton JButton addbutton = new JButton("add"); 29 30 JButton Methods JLabel String gettext() void settext(string newtext) Puts text on screen No borders, no actions, no background color (transparent) void setenabled(boolean enabled); default is true disabled button is "greyed out", no graphic reaction when clicked JLabel addlabel = new JLabel("amount to add: "); 31 32
JLabel Methods Text Components String gettext() void settext(string newtext) two kinds: text field (one line) text area (multiple lines) 33 34 one line only space for entering/displaying text JTextField "editable " JTextArea like a JTextField, but multiple lines not "editable" JTextField addfield = new JTextField(10); width in "m JTextField multfield = new JTextField(10); spaces" JTextArea quotetextarea = new JTextArea(3,20); JTextField totalfield = new JTextField(10); totalfield.seteditable(false); JTextArea databasearea = new JTextArea(20, 30); databasearea.seteditable(false); 35 36
Methods For Text Components String gettext() void settext(string newtext) 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 37 38 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 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 39 40
Sequence of Events Set-up (usually in constructor): create button create listener register listener with button you write this code Demo: Baby Calculator Three different styles: inner listener class(es) use frame as listener anonymous inner classes 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 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 Outline 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 drawing pictures dynamically E. Mouse Events & Timers reacting to mouse clicks using timers for animation 43 44
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 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 45 46 Graphics methods Note About Coordinates 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! Swing uses x & y coordinates, different from math x positive x: to the right positive y: down y 47 48
Simple Example Program start with a static display; add actions 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 49 50 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! 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 drawing pictures dynamically Outline E. Mouse Events & Timers reacting to mouse clicks using timers for animation 51 52
Part E: Timers & Mouse Events Timers & Animation 1. Using a timer for animation 2. Reacting to mouse events Goal: Picture changes at frequent intervals without user intervention. To accomplish this: program generates its own events that change the screen 53 54 Swing Timer Class Example Swing Timer: object that generates events at intervals. Timer(int delay, ActionListener listener) creates a timer, not started yet Program from last time: box with lines, grows & shrinks in response to buttons. New version: grows & shrinks by itself. demo... Timer timr = new Timer(500, new MyListenerClass()); will generate an ActionEvent every 500 milliseconds Caution: No guarantee events will occur exactly twice a second. Depends on program & system load. timr.start(); // timr starts generating events timr.stop(); // timr stops generating events 55 56
Review of Events & Listeners So Far We have discussed one kind of event: ActionEvent. Generated by several kinds of components: buttons text fields menu items ActionEvent object is simple: contains source of event Listener interface: ActionListener One method only -- actionperformed. Mouse Events A mouse event can be generated for mouse events inside any component. Kinds of mouse events: mouse enters the component mouse leaves the component mouse button pressed mouse button released mouse button clicked (pressed & released @ same spot) 57 58 MouseEvent Objects MouseListener interface A MouseEvent describes a mouse event. Methods to get location where event happened: getx() gety() public interface MouseListener { void mouseclicked(mouseevent e); void mouseentered(mouseevent e); void mouseexited(mouseevent e); void mousepressed(mouseevent e); void mousereleased(mouseevent e); } quick demo... 59 60
Helpful Class: MouseAdapter Next example: I want to react to mouse clicks, not the other 4 kinds of events. Straightforward way: create a MouseListener class, 4 of the methods will have empty bodies. Example: Line Drawing Program demo... Shortcut: MouseAdapter is a class that implements MouseListener. All 5 method bodies are empty. My example: extend MouseAdapter and just have to override one method. 61 62 Suggestion For Assignment 4 Use mousepressed instead of mouseclicked. Why? Hard to keep it mouse absolutely still during a click. 63