1 / 50

Swing II: WindowListener Interface and Implementation

Learn how to use WindowListener interface methods, icons with Swing components, and extend JFrame with inner classes for event handling in Java Swing.

vivianx
Download Presentation

Swing II: WindowListener Interface and Implementation

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Swing II

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

  3. Windowlistener interface

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

  5. WindowListener interface • Recall that the JFramesetDefaultCloseOperation is very limited. • Instead, you may respond in any manner you wish by implementing the WindowListenerinteface and then by using the setWindowListener method.

  6. 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.

  7. 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.

  8. 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 ) { }

  9. 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 ) { } }

  10. 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.

  11. Inner classes • Ex. public classMyOuterClass { … private classMyInnerClass { … } … }

  12. 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.

  13. 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() ); } … }

  14. 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.

  15. 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.

  16. icons

  17. 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.

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

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

  20. scrollbars

  21. 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.

  22. 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 ) policies: • JScrollPane.VERTICAL_SCROLLBAR_ALWAYS • JScrollPane.VERTICAL_SCROLLBAR_NEVER • JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED

  23. The graphics class

  24. 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 )

  25. 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, intstartAngle, intarcAngle ) • Draws the outline of a circular or elliptical arc covering the specified rectangle.

  26. 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, intnPoints ) • Draws a closed polygon defined by arrays of x and y coordinates. void drawPolyline ( int[] xPoints, int[] yPoints, intnPoints ) • Draws a sequence of connected lines defined by arrays of x and y coordinates.

  27. 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, intarcWidth, intarcHeight ) • 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.

  28. Graphics class methods • Method summary: void fillArc ( int x, int y, int width, int height, intstartAngle, intarcAngle ) • 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, intnPoints ) • 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.

  29. Graphics class methods • Method summary: void fillRoundRect ( int x, int y, int width, int height, intarcWidth, intarcHeight ) • 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. FontMetricsgetFontMetrics ( ) • Gets the font metrics of the current font. FontMetricsgetFontMetrics ( Font f ) • Gets the font metrics for the specified font.

  30. 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.

  31. 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).

  32. 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]

  33. 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]

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

  35. 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 ); g.drawString( “hello”, x, y );

  36. 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!

  37. 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).

  38. Additional information Not in the textbook

  39. Additional listeners • MouseListener • MouseMotionListener • MouseWheelListener • KeyListener • WindowStateListener • WindowFocusListener

  40. 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.

  41. 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.

  42. MouseEvent class Method summary: intgetButton ( ) • Returns which, if any, of the mouse buttons has changed state. intgetClickCount ( ) • Returns the number of mouse clicks associated with this event. intgetX ( ) • Returns the horizontal x position of the event relative to the source component.

  43. MouseEvent class Method summary: intgetY ( ) • Returns the vertical y position of the event relative to the source component. String paramString ( ) • Returns a parameter string identifying this event. intgetModifiersEx ( ) (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.

  44. 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.

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

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

  47. 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).

  48. 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.

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

  50. 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.

More Related