




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





Lecture 18 CS211 โ Summer 2008
2
y โClassicโ view of computer programs: transform inputs to outputs, stop
y Event-driven programs: interactive, long-running ย Servers interact with clients ย Applications interact with user(s)
input events
output events
3
y Interacting with a program ย Program-Driven ย Statements execute in sequential, predetermined order ย Use keyboard or file I/O, but program determines when that happens ย Usually single-threaded ย Event-Driven ย Program waits for user input to activate certain statements ย Typically uses a GUI (Graphical User Interface) ย Often multi-threaded
y Design...Which to pick? ย Program called by another program? ย Program used at command line? ย Program interacts often with user? ย Program used in window environment?
y How does Java do GUIs? (^4)
y Java Foundation Classes ย Classes for building GUIs ย Major components ย awt and swing ย Pluggable look-and-feel support ย Accessibility API ย Java 2D API ย Drag-and-drop Support ย Internationalization
y Our main focus: Swing ย Building blocks of GUIs ย Windows & components ย User interactions ย Built upon the AWT (Abstract Window Toolkit) ย Java event model
y Javaโs support for cross-platform GUIs is one of its main selling points
y Pluggable Look-and-Feel Support ย Controls look-and-feel for particular windowing environment ย E.g., Java, Windows, Motif, Mac
y Accessibility API ย Supports assistive technologies such as screen readers and Braille
y Java 2D ย Drawing ย Includes rectangles, lines, circles, images, ...
y Drag-and-drop ย Support for drag and drop between Java application and a native application
y Internationalization ย Support for other languages
y Statics: whatโs drawn on the screen ย Components ย buttons, labels, lists, sliders, menus, ... ย Containers: components that contain other components ย frames, panels, dialog boxes, ... ย Layout managers: control placement and sizing of components
y Dynamics: user interactions ย Events ย button-press, mouse-click, key-press, ... ย Listeners: an object that responds to an event ย Helper classes ย Graphics, Color, Font, FontMetrics, Dimension, ...
7
import javax.swing.*;
public class Basic1 { public static void main(String[] args) { //create the window JFrame f = new JFrame("Basic Test!"); //quit Java after closing the window f.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); f.setSize(200, 200); //set size in pixels f.setVisible(true); //show the window } }
8
import javax.swing.*; public class Basic2 extends JFrame {
public static void main(String[] args) { new Basic2(); } public Basic2() { setTitle("Basic Test2!"); //set the title //quit Java after closing the window setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); setSize(200, 200); //set size in pixels setVisible(true); //show the window } }
9
import javax.swing.; import java.awt.; import java.awt.event.*; public class Intro extends JFrame { private int count = 0; privateprivate JButtonJLabel labelmyButton = new = newJLabel("Count: JButton("Push " +Me!"); count);
publicsetDefaultCloseOperation(JFrame. Intro() { EXIT_ON_CLOSE ); setLayout(new FlowLayout(FlowLayout. LEFT )); //set layout manager add(myButton);add(label); //add components label.setPreferredSize(new Dimension(60, 10)); myButton.addActionListener(new ActionListener() { publiccount++; void actionPerformed(ActionEvent e) { }label.setText("Count:^ "^ +^ count); }); pack(); setVisible(true); } publictry static{ void main(String[] args) { UIManager. setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); }new catch Intro(); (Exception exc) {} } } 10
import javax.swing.; import java.awt.; public class ComponentExamples extends JFrame { public ComponentExamples() { setLayout(new FlowLayout(FlowLayout. LEFT )); add(new JButton("Button")); add(new JLabel("Label")); add(new JComboBox(new String[] { "A", "B", "C" })); add(new JCheckBox("JCheckBox")); add(new JSlider(0, 100)); add(new JColorChooser()); setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); pack(); setVisible(true); } public static void main(String[] args) { try { UIManager. setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); } catch (Exception exc) {} new ComponentExamples(); } }
19
BorderLayout Example
import javax.swing.; import java.awt.; public classpublic static Statics2 void {main(String[] args) { new S2GUI(); } } class ColoredJPanel extends JPanel { Color color; ColoredJPanel(Color color) { this.color = color; } public void paintComponent(Graphics g) { g.setColor(color); g.fillRect(0, 0, 400, 400); } } class S2GUI extends JFrame { public S2GUI() { setTitle("Statics2"); setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); setSize(400, 400); add(new ColoredJPanel(Color. RED ), BorderLayout. NORTH ); add(new ColoredJPanel(Color. GREEN ), BorderLayout. SOUTH ); add(new ColoredJPanel(Color. BLUE ), BorderLayout. WEST ); add(new ColoredJPanel(Color. YELLOW ), BorderLayout. EAST ); add(new ColoredJPanel(Color. BLACK ), BorderLayout. CENTER ); setVisible(true); } } 20
GridLayout Example
import javax.swing.; import java.awt.; public class Statics3 { public static void main(String[] args) { new S3GUI(); } } class S3GUI extends JFrame { static final int DIM = 25; static final int SIZE = 12; static final int GAP = 1; publicsetTitle("Statics3"); S3GUI() { setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); setLayout(new GridLayout( DIM , DIM , GAP , GAP )); for (int i = 0; i < DIM * DIM ; i++) add(new MyPanel()); pack(); setVisible(true); } class MyPanel extends JPanel { MyPanel() { setPreferredSize(new Dimension( SIZE , SIZE )); } public void paintComponent(Graphics g) { float gradient = 1f - ((float)Math. abs (getX() - getY()))/(float)(( SIZE + GAP ) * DIM ); g.setColor(new Color(0f, 0f, gradient));g.fillRect(0, 0, getWidth(), getHeight()); } } }
21
y CardLayout
ย Tabbed index card look from Windows
y GridBagLayout
ย Most versatile, but complicated
y Custom ย Can define your own layout manager ย But best to try Java's layout managers first...
y Null ย No layout manager ย Programmer must specify absolute locations ย Provides great control, but can be dangerous because of platform dependency (^22)
y AWT ย Initial GUI toolkit for Java ย Provided a โJavaโ look and feel ย Basic API: java.awt.*
y Swing ย More recent (since Java 1.2) GUI toolkit ย Added functionality (new components) ย Supports look and feel for various platforms (Windows, Motif, Mac) ย Basic API: javax.swing.*
y Did Swing replaced AWT? ย Not quite: both use the AWT event model
y Intro.java ย Button & counter
y Basic1.java ย Create a window
y Basic2.java ย Create a window using a constructor
y Calculator.java ย Shows use of JOptionPane to produce standard dialogs
y ComponentExamples.java ย Sample components y Statics1.java ย FlowLayout example y Statics2.java ย BorderLayout example y Statics3.java ย GridLayout example y LayoutDemo.java ย Multiple layouts
25
y Statics: whatโs drawn on the screen ย Components ย buttons, labels, lists, sliders, menus, ... ย Containers: components that contain other components ย frames, panels, dialog boxes, ... ย Layout managers: control placement and sizing of components
y Dynamics: user interactions ย Events ย button-press, mouse-click, key-press, ... ย Listeners: an object that responds to an event ย Helper classes ย Graphics, Color, Font, FontMetrics, Dimension, ...
26
ย What actions? events ย Need to write code that knows what to do when an event occurs ย In Java, you specify what happens by providing an object that โhearsโ the event ย In other languages, you specify what happens in response to an event by providing a function
ย Events ย Event listeners
Event listener
Event listener
27
importimport javax.swing.;java.awt.; import java.awt.event.*; public class Intro extends JFrame { private int count = 0; private JButton myButton = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); publicsetDefaultCloseOperation(JFrame. Intro() { EXIT_ON_CLOSE ); setLayout(new FlowLayout(FlowLayout. LEFT )); //set layout manager add(myButton);add(label); //add components label.setPreferredSize(new Dimension(60, 10)); myButton.addActionListener(new ActionListener() { publiccount++; void actionPerformed(ActionEvent e) { label.setText("Count: " + count); });} pack(); setVisible(true); } public static void main(String[] args) { try (^) UIManager.{ setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); }new catch Intro(); (Exception exc) {} } }
28
importimport javax.swing.;java.awt.; import java.awt.event.*; public class Intro extends JFrame { private int count = 0; private JButton myButton = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); publicsetDefaultCloseOperation(JFrame. Intro() { EXIT_ON_CLOSE ); setLayout(new FlowLayout(FlowLayout. LEFT )); //set layout manager add(myButton);add(label); //add components label.setPreferredSize(new Dimension(60, 10)); myButton.addActionListener(new ActionListener() { publiccount++; void actionPerformed(ActionEvent e) { label.setText("Count: " + count); });} pack(); setVisible(true); } public static void main(String[] args) { try (^) UIManager.{ setLookAndFeel (UIManager. getSystemLookAndFeelClassName ()); }new catch Intro(); (Exception exc) {} } }
ย User (or program) does something to a component ย clicks on a button, resizes a window, ... ย Java issues an event object describing the event ย A special type of object (a listener) โhearsโ the event ย The listener has a method that โhandlesโ the event ย The handler does whatever the programmer programmed
ย Events : How components issue events ย Listeners : How to make an object that listens for events ย Handlers : How to write a method that responds to an event
y An Event is a Java object ย It represents an action that has occurred โ mouse clicked, button pushed, menu item selected, key pressed, ... ย Events are normally created by the Java runtime system ย You can create your own events, but this is unusual
y Most events are in java.awt.event ย Some events are in javax.swing.event y All events are subclasses of AWTEvent
AWTEvent ActionEvent ComponentEvent InputEvent MouseEvent KeyEvent
37
import javax.swing.; import java.awt.; import java.awt.event.*; public class ListenerExample2 extends JFrame { private int count; private JButton b = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); class Helper implements ActionListener { public void actionPerformed(ActionEvent e) { count++; label.setText("Count: " + count); } } public static void main(String[] args) { JFrame f = new ListenerExample2(); f.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); f.setSize(200,100); f.setVisible(true); } public ListenerExample2() { setLayout(new FlowLayout(FlowLayout. LEFT )); add(b); add(label); b.addActionListener(new Helper()); } } 38
import javax.swing.; import java.awt.; import java.awt.event.*; public class ListenerExample3 extends JFrame { private int count; private JButton b = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); public static void main (String[] args) { JFrame f = new ListenerExample3(); f.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE ); f.setSize(200,100); f.setVisible(true); } public ListenerExample3() { setLayout(new FlowLayout(FlowLayout. LEFT )); add(b); add(label); b.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { count++; label.setText("Count: " + count); } }); } }
39
ย For instance, you may be interested only in mouse clicks
ย An adapter is a predefined class that implements all the methods of the corresponding Listener ย Example: MouseInputAdapter is a class that implements all the methods of interface MouseInputListener ย The adapter methods do nothing ย To easily create your own listener, you extend the adapter class, overriding just the methods that you actually need
40
import javax.swing.; import javax.swing.event.; import java.awt.; import java.awt.event.; public class AdapterExample extends JFrame { private int count; private JButton b = new JButton("Mouse Me!"); private JLabel label = new JLabel("Count: " + count); class Helper extends MouseInputAdapter { public void mouseEntered(MouseEvent e) { count++; label.setText("Count: " + count); } } public static void main(String[] args) { JFrame f = new AdapterExample(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200,100); f.setVisible(true); } public AdapterExample() { setLayout(new FlowLayout(FlowLayout.LEFT)); add(b); add(label); b.addMouseListener(new Helper()); } }
ย Can use event.getSource() to identify the component that generated the event
y For a drawing area, extend JPanel and override the method public void paintComponent(Graphics g)
y paintComponent contains the code to completely draw everything in your drawing panel
y Do not call paintComponent directly โ instead, request that the system redraw the panel at the next convenient opportunity by calling myPanel.repaint()
y repaint() requests a call paintComponent() โsoonโ ย repaint(ms) requests a call within ms milliseconds ย Avoids unnecessary repainting ย 16ms is a good default value
y The Graphics class has methods for colors, fonts, and various shapes and lines ย setColor(Color c) ย drawOval(int x, int y, int width, int height) ย fillOval(int x, int y, int width, int height) ย drawLine(int x1, int y1, int x2, int y2) ย drawString(String str, int x, int y)
y Take a look at ย java.awt.Graphics (for basic graphics) ย java.awt.Graphics2D (for more sophisticated control) ย The 2D Graphics Trail: http://java.sun.com/docs/books/tutorial/2d/index.html