Swing II.

Slides:



Advertisements
Similar presentations
Custom Painting Gestione della Grafica customizzata Vedi anche:
Advertisements

Handling Mouse Events Event-Driven Programming Approccio standard per programmare GUI In contrapposizione al polling offre: - Maggiore flessibilità - Minor.
Applets and Graphics.
Chapter 15 Graphics. To paint, you need to specify where to paint. Each component has its own coordinate system with the origin (0, 0) at the upper-left.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Graphics Chapter 16.  If you want to draw shapes such as a bar chart, a clock, or a stop sign, how do you do it?
Graphics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Event-Driven Programming You might have realized in creating a GUI and clicking on the JButtons that nothing happens Clicking on a JButton causes the JVM.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
GUI and Swing, part 2 The illustrated edition. Scroll bars As we have previously seen, a JTextArea has a fixed size, but the amount of text that can be.
© The McGraw-Hill Companies, 2006 Chapter 14 Abstraction, inheritance and interfaces.
Jan Event Handling -1.1 Yangjun Chen Dept. Business Computing University of Winnipeg.
CS221 © 2007 Ray S. Babcock Menus, Toolbars, and a Mouse Appendix C.6-C.7.
Event Handling Events and Listeners Timers and Animation.
Slides prepared by Rose Williams, Binghamton University Chapter 18 Swing II.
May 11, 1998CS102-02Lecture 7-1 More Graphics in Java CS Lecture 7-1 A picture's worth a thousand words.
Event Handling n Events: an event is an object that describes a state change in a source. n Event Sources: A source is an object that generates an event.
Event Handling. In this class we will cover: Keyboard Events Mouse Events Focus Events Action Interface Multicasting.
Chapter 18 Swing II Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
28-Aug-15 Air Force Institute of Technology Electrical and Computer Engineering Object-Oriented Programming Design Topic : Event Handling – GUI Part II.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Graphics in Java hussein suleman uct cs
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
Applets Applet is java program that can be embedded into HTML pages. Java applets runs on the java enabled web browsers such as mozilla and internet explorer.
Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
Omer Boyaci.  GUIs are event driven.  When the user interacts with a GUI component, the interaction—known as an event—drives the program to perform.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Merete S COLLEGEFACULTY OF ENGINEERING & SCIENCE Graphics ikt403 – Object-Oriented Software Development.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
Universidad Nacional de Colombia Facultad de Ingeniería Departamento de Sistemas ertificación en AVA.
CMSC 341 Making Java GUIs Functional. 09/29/2007 CMSC 341 Events 2 More on Swing Great Swing demo at /demos/jfc/SwingSet2/SwingSet2Plugin.html.
Object Oriented Programming.  Interface  Event Handling.
Agenda Introduction. Event Model. Creating GUI Application. Event Examples.
Index Event Handling Events Event Source Event Listener Event Classes Action Event Class Adjustment event Class Event Source Event Listener Interface Using.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
(c) by Elizabeth Sugar Boese.1 Chapter 6 Events - Lecture Slides.
Event Handling. User actions are called “events” – Low-level window events Window changes – Low-level component events Mouse events, Keyboard events,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
 Many event-listener interfaces contain multiple methods.  An adapter class implements an interface and provides a default implementation (with an empty.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
CSI 3125, Preliminaries, page 1 Event Handling. CSI 3125, Preliminaries, page 2 Event Handling An Event Change in the state of an object is known as event.
Slides prepared by Rose Williams, Binghamton University Chapter 19 Swing II.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
CS 240 Week 9. EventQueue.invokeLater In Swing, all user interface operations must occur on the “UI thread” – All components should be created on the.
Jaeki Song ISQS6337 JAVA Lecture 10 Applets. Jaeki Song ISQS6337 JAVA Applet Applets run within the Web browser environment –Applets bring dynamic interaction.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
10/20/2005week71 Graphics, mouse and mouse motion events, KeyEvent Agenda Classes in AWT for graphics Example java programs –Graphics –Mouse events –Mouse.
12 Graphics and Java 2D™.
CHAPTER Reacting to the user.
Advanced User Interfaces
Computer Science 209 Graphics and GUIs.
Chapter 18 Swing II Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage Copyright © 2016 Pearson Inc.
Graphics Applets By Mr. Dave Clausen
Programming in Java Event Handling
Miscellaneous Topics #6: Polygons GUI Components and Event Handlers
Introduction to Computing Using Java
GUI Programming using Java - Mouse Events
Web Design & Development Lecture 12
Web Design & Development Lecture 13
Events, Event Handlers, and Threads
Making Java GUIs Functional
Presentation transcript:

Swing II

Swing II Topics WindowListener interface Icons Scrollbars The Graphics class Colors Fonts & the drawString method

Windowlistener interface

WindowListener interface Must implement WindowListener interface (java.awt.event). All methods receive a WindowEvent (java.awt.event).

WindowListener interface Recall that the JFrame setDefaultCloseOperation is very limited. Instead, you may respond in any manner you wish by implementing the WindowListener inteface and then by using the setWindowListener method.

WindowListener interface Method summary: void windowActivated ( WindowEvent e ) Invoked when the Window is set to be the active Window. void windowClosed ( WindowEvent e ) Invoked when a window has been closed as the result of calling dispose on the window. void windowClosing ( WindowEvent e ) Invoked when the user attempts to close the window from the window's system menu.

WindowListener interface Method summary: void windowDeactivated ( WindowEvent e ) Invoked when a Window is no longer the active Window. void windowDeiconified ( WindowEvent e ) Invoked when a window is changed from a minimized to a normal state. void windowIconified ( WindowEvent e ) Invoked when a window is changed from a normal to a minimized state.

WindowListener interface Method summary: void windowOpened ( WindowEvent e ) Invoked the first time a window is made visible. You do not need to fully implement all methods. You can simply define them with an empty block: public void windowDeiconified ( WindowEvent e ) { }

Basic WindowListener template import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class MyWindowListener implements WindowListener { public void windowActivated ( WindowEvent e ) { } public void windowClosed ( WindowEvent e ) { } public void windowClosing ( WindowEvent e ) { } public void windowDeactivated ( WindowEvent e ) { } public void windowDeiconified ( WindowEvent e ) { } public void windowIconified ( WindowEvent e ) { } public void windowOpened ( WindowEvent e ) { } }

Extending JFrame and implementing some Listener We have 3 architectural options: Class A extends JFrame; class B implements some Listener. Class A extends JFrame and implements some Listener. Class A extends JFrame and class A contains an inner class B that implements some Listener.

Inner classes Ex. public class MyOuterClass { … private class MyInnerClass { }

Inner classes Advantages: Can be used to make the outer class self-contained. Inner and outer classes have access to each other’s private members. Private inner classes cannot be accessed by name outside of the defining outer class.

Extending JFrame & implementing a WindowListener in an inner class … public class MyFrame extends JFrame { private class MyWindowListener implements WindowListener { public void windowActivated ( WindowEvent e ) { } public void windowClosed ( WindowEvent e ) { } public void windowClosing ( WindowEvent e ) { } public void windowDeactivated ( WindowEvent e ) { } public void windowDeiconified ( WindowEvent e ) { } public void windowIconified ( WindowEvent e ) { } public void windowOpened ( WindowEvent e ) { } } public MyFrame ( ) { addWindowListener( new MyWindowListener() );

WindowAdapter class An abstract adapter class for receiving window events. The methods in this class are empty. This class exists as convenience for creating listener objects.

WindowAdapter class Extend this class to create a WindowEvent listener and only override the methods for the events of interest. If you implement the WindowListener interface, you have to define all of the methods in it. This abstract class defines null (i.e., empty) methods for them all, so you can only have to define methods for events you care about.) Create a listener object using the extended class and then register it with a Window using the window's addWindowListener method. When the window's status changes by virtue of being opened, closed, activated or deactivated, iconified or deiconified, the relevant method in the listener object is invoked, and the WindowEvent is passed to it.

icons

Icons Simply a (typically small) picture. JLabels, JButtons, and JMenuItems can have: icons strings icons and strings nothing at all If the item doesn’t have any associated text, use the setActionCommand method to explicitly assign a command string to the item.

Icons Creating icons from image files: Adding an icon to a label: ImageIcon dukeIcon = new ImageIcon( “duke_waving.gif” ); Adding an icon to a label: JLabel dukeLabel = new JLabel( “wood check” ); dukeLabel.setIcon( dukeIcon ); JLabel dukeLabel = new JLabel( dukeIcon );

Icons Icons may be used with buttons and menu items too: JButton happyButton = new JButton( “happy” ); ImageIcon happyIcon = new ImageIcon( “smiley.gif” ); happyButton.setIcon( happyIcon );

scrollbars

Scrollbars Create the object to be scrolled: JTextArea memo = new JTextArea( 15, 30 ); Create the JScrollPane: public JScrollPane ( Component objectToBeScrolled ) Add the JScrollPane to a container such as JPanel or JFrame.

Scrollbars JScrollPane public JScrollPane ( Component objectToBeScrolled ) public void setHorizontalScrollBarPolicy ( int policy ) policies: JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS JScrollPane.HORIZONTAL_SCROLLBAR_NEVER JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED public void setVerticalScrollBarPolicy ( int policy ) JScrollPane.VERTICAL_SCROLLBAR_ALWAYS JScrollPane.VERTICAL_SCROLLBAR_NEVER JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED

The graphics class

The Graphics class Coodinate system and origin: (0,0) ----------> +x | v +y JFrame’s paint method draws whatever needs to be drawn. public void paint ( Graphics g )

Graphics class methods Method summary: void clearRect ( int x, int y, int width, int height ) Clears the specified rectangle by filling it with the background color of the current drawing surface. void draw3DRect ( int x, int y, int width, int height, boolean raised ) Draws a 3-D highlighted outline of the specified rectangle. void drawArc ( int x, int y, int width, int height, int startAngle, int arcAngle ) Draws the outline of a circular or elliptical arc covering the specified rectangle.

Graphics class methods Method summary: void drawLine ( int x1, int y1, int x2, int y2 ) Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. void drawOval ( int x, int y, int width, int height ) Draws the outline of an oval. void drawPolygon ( int[] xPoints, int[] yPoints, int nPoints ) Draws a closed polygon defined by arrays of x and y coordinates. void drawPolyline ( int[] xPoints, int[] yPoints, int nPoints ) Draws a sequence of connected lines defined by arrays of x and y coordinates.

Graphics class methods Method summary: void drawRect ( int x, int y, int width, int height ) Draws the outline of the specified rectangle. void drawRoundRect ( int x, int y, int width, int height, int arcWidth, int arcHeight ) Draws an outlined round-cornered rectangle using this graphics context's current color. void drawString ( String str, int x, int y ) Draws the text given by the specified string, using this graphics context's current font and color. void fill3DRect ( int x, int y, int width, int height, boolean raised ) Paints a 3-D highlighted rectangle filled with the current color.

Graphics class methods Method summary: void fillArc ( int x, int y, int width, int height, int startAngle, int arcAngle ) Fills a circular or elliptical arc covering the specified rectangle. void fillOval ( int x, int y, int width, int height ) Fills an oval bounded by the specified rectangle with the current color. void fillPolygon ( int[] xPoints, int[] yPoints, int nPoints ) Fills a closed polygon defined by arrays of x and y coordinates. void fillPolygon ( Polygon p ) Fills the polygon defined by the specified Polygon object with the graphics context's current color. void fillRect ( int x, int y, int width, int height ) Fills the specified rectangle.

Graphics class methods Method summary: void fillRoundRect ( int x, int y, int width, int height, int arcWidth, int arcHeight ) Fills the specified rounded corner rectangle with the current color. Color getColor ( ) Gets this graphics context's current color. Font getFont ( ) Gets the current font. FontMetrics getFontMetrics ( ) Gets the font metrics of the current font. FontMetrics getFontMetrics ( Font f ) Gets the font metrics for the specified font.

Graphics class methods Method summary: void setColor ( Color c ) Sets this graphics context's current color to the specified color. void setFont ( Font font ) Sets this graphics context's font to the specified font. void translate ( int x, int y ) Translates the origin of the graphics context to the point (x, y) in the current coordinate system.

Drawing with the Graphics class … public class Face extends JFrame { public void paint ( Graphics g ) { super.paint( g ); g.setColor( Color.BLUE ); g.drawLine( 55, 60, 75, 60 ); } Typically, one overrides paint but never calls it directly. Additionally, there is a repaint method. Typically, one calls repaint when it is necessary to redraw the contents of the frame (but one never overrides repaint).

Colors We saw how we can call setColor in our paint method to change colors. We may use the predefined colors such as Color.BLUE, Color.CYAN, etc. Colors are represented by triples of RGB values: Color brown = new Color( 200, 150, 0 ); where each int component is in [0..255]

Colors Other useful methods: public Color brighter ( ) Returns a brighter version of the calling object’s color. public Color darker ( ) Returns a darker version of the calling object’s color. new Color ( 0.5f, 1.0f, (float)0.2 ); Where each float rgb component is in [0.0 .. 1.0]

Colors Color c = JColorChooser.showDialog( null, "JColorChooser", null );

Fonts & the drawString method Recall the drawString method: g.drawString( “hello”, x, y ); To change the current font: Font f = new Font( “SansSerif”, Font.PLAIN, 24 ); … g.setFont( f );

Fonts & the drawString method Say the user picks a different font from a menu. What sequence of events occurs? How do we then change the appearance of the text in our paint/drawing program? Note, we can’t call paint() directly!

Forcing a change in appearance Note that Component is a superclass of many, many things. Simply call repaint() to repaint yourself (cause paint() to be called).

Additional information Not in the textbook

Additional listeners MouseListener MouseMotionListener MouseWheelListener KeyListener WindowStateListener WindowFocusListener

MouseListener interface Method summary: void mouseClicked ( MouseEvent e ) Invoked when the mouse button has been clicked (pressed and released) on a component. void mouseEntered ( MouseEvent e ) Invoked when the mouse enters a component. void mouseExited ( MouseEvent e ) Invoked when the mouse exits a component.

MouseListener interface Method summary: void mousePressed ( MouseEvent e ) Invoked when a mouse button has been pressed on a component. void mouseReleased ( MouseEvent e ) Invoked when a mouse button has been released on a component. Also MouseAdapter & MouseInputAdapter classes.

MouseEvent class Method summary: int getButton ( ) Returns which, if any, of the mouse buttons has changed state. int getClickCount ( ) Returns the number of mouse clicks associated with this event. int getX ( ) Returns the horizontal x position of the event relative to the source component.

MouseEvent class Method summary: int getY ( ) String paramString ( ) Returns the vertical y position of the event relative to the source component. String paramString ( ) Returns a parameter string identifying this event. int getModifiersEx ( ) (inherited from InputEvent) Returns the extended modifier mask for this event. Extended modifiers represent the state of all modal keys, such as ALT, CTRL, META, and the mouse buttons just after the event occurred.

MouseMotionListener interface Method summary: void mouseDragged ( MouseEvent e ) Invoked when a mouse button is pressed on a component and then dragged. void mouseMoved ( MouseEvent e ) Invoked when the mouse cursor has been moved onto a component but no buttons have been pushed. Also MouseMotionAdapter & MouseInputAdapter classes.

MouseWheelListener interface Method summary: void mouseWheelMoved ( MouseWheelEvent e ) Invoked when the mouse wheel is rotated. No MouseWheelAdapter!

MouseWheelEvent class Method summary: int getScrollAmount ( ) Returns the number of units that should be scrolled in response to this event. int getWheelRotation ( ) Returns the number of "clicks" the mouse wheel was rotated.

KeyListener interface Added to a component by its addKeyListener method. KeyAdapter class available as well. Method summary: void keyPressed ( KeyEvent e ) Invoked when a key has been pressed (low level). void keyReleased ( KeyEvent e ) Invoked when a key has been released (low level). void keyTyped ( KeyEvent e ) Invoked when a key has been typed (higher level).

KeyEvent class Indicates what key was pressed. Defines constants for function and arrow keys. Allows one to detect if modifiers (Alt, Ctrl, Shift) were also pressed.

WindowStateListener interface Method summary: void windowStateChanged ( WindowEvent e ) Invoked when window state is changed. WindowEvent & WindowAdapter classes were already discussed.

WindowFocusListener interface Method summary: void windowGainedFocus ( WindowEvent e ) Invoked when the Window is set to be the focused Window, which means that the Window, or one of its subcomponents, will receive keyboard events. void windowLostFocus ( WindowEvent e ) Invoked when the Window is no longer the focused Window, which means that keyboard events will no longer be delivered to the Window or any of its subcomponents. WindowEvent & WindowAdapter classes were already discussed.