Presentation is loading. Please wait.

Presentation is loading. Please wait.

Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors.

Similar presentations


Presentation on theme: "Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors."— Presentation transcript:

1 Swing II

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

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

4 WindowListener interface Recall that the Jframe setDefaultCloseOperation is very limited. 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. Instead, you may respond in any manner you wish by implementing the WindowListener inteface and then by using the setWindowListener method.

5 WindowListener interface Method summary: void windowActivated ( WindowEvent e ) Invoked when the Window is set to be the active Window. 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. 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. Invoked when the user attempts to close the window from the window's system menu.

6 WindowListener interface Method summary: void windowDeactivated ( WindowEvent e ) Invoked when a Window is no longer the active Window. 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. 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. Invoked when a window is changed from a normal to a minimized state.

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

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

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

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

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

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

13 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. An abstract adapter class for receiving window events. The methods in this class are empty. This class exists as convenience for creating listener objects.

14 WindowAdapter class Extend this class to create a WindowEvent listener and 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.) Extend this class to create a WindowEvent listener and 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. 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.

15 ICONS

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

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

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

19 SCROLLBARS

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

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

22 THE GRAPHICS CLASS

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

24 Graphics class methods Method summary: Method summary: voidclearRect ( int x, int y, int width, int height ) Clears the specified rectangle by filling it with the background color of the current drawing surface. Clears the specified rectangle by filling it with the background color of the current drawing surface. voiddraw3DRect ( int x, int y, int width, int height, boolean raised ) Draws a 3-D highlighted outline of the specified rectangle. Draws a 3-D highlighted outline of the specified rectangle. voiddrawArc ( 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. Draws the outline of a circular or elliptical arc covering the specified rectangle.

25 Graphics class methods Method summary: Method summary: voiddrawLine ( 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. Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. voiddrawOval ( int x, int y, int width, int height ) Draws the outline of an oval. Draws the outline of an oval. voiddrawPolygon ( int[] xPoints, int[] yPoints, int nPoints ) Draws a closed polygon defined by arrays of x and y coordinates. Draws a closed polygon defined by arrays of x and y coordinates. voiddrawPolyline ( int[] xPoints, int[] yPoints, int nPoints ) Draws a sequence of connected lines defined by arrays of x and y coordinates. Draws a sequence of connected lines defined by arrays of x and y coordinates.

26 Graphics class methods Method summary: Method summary: voiddrawRect ( int x, int y, int width, int height ) Draws the outline of the specified rectangle. Draws the outline of the specified rectangle. voiddrawRoundRect ( 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. Draws an outlined round-cornered rectangle using this graphics context's current color. voiddrawString ( String str, int x, int y ) Draws the text given by the specified string, using this graphics context's current font and color. Draws the text given by the specified string, using this graphics context's current font and color. voidfill3DRect ( int x, int y, int width, int height, boolean raised ) Paints a 3-D highlighted rectangle filled with the current color. Paints a 3-D highlighted rectangle filled with the current color.

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

28 Graphics class methods Method summary: Method summary: voidfillRoundRect ( int x, int y, int width, int height, int arcWidth, int arcHeight ) Fills the specified rounded corner rectangle with the current color. Fills the specified rounded corner rectangle with the current color. ColorgetColor ( ) Gets this graphics context's current color. Gets this graphics context's current color. FontgetFont ( ) Gets the current font. Gets the current font. FontMetricsgetFontMetrics ( ) Gets the font metrics of the current font. Gets the font metrics of the current font. FontMetricsgetFontMetrics ( Font f ) Gets the font metrics for the specified font. Gets the font metrics for the specified font.

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

30 … public class Face extends JFrame { … public void paint ( Graphics g ) { super.paint( g ); g.setColor( Color.BLUE ); g.drawLine( 55, 60, 75, 60 ); …}…} Drawing with the graphics class 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).

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

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

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

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

35 Fonts & the drawString method Say the user picks a different font from a menu. Say the user picks a different font from a menu. 1. What sequence of events occur? 2. How do we then change the appearance of the text in our paint/drawing program?

36 Additional information Not in the text

37 Additional listeners MouseListener MouseListener MouseMotionListener MouseMotionListener MouseWheelListener MouseWheelListener KeyListener KeyListener WindowStateListener WindowStateListener WindowFocusListener WindowFocusListener

38 MouseListener interface Method summary: voidmouseClicked ( MouseEvent e ) Invoked when the mouse button has been clicked (pressed and released) on a component. Invoked when the mouse button has been clicked (pressed and released) on a component. voidmouseEntered ( MouseEvent e ) Invoked when the mouse enters a component. Invoked when the mouse enters a component. voidmouseExited ( MouseEvent e ) Invoked when the mouse exits a component. Invoked when the mouse exits a component.

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

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

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

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

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

44 MouseWheelEvent class Method summary: intgetScrollAmount ( ) Returns the number of units that should be scrolled in response to this event. 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. Returns the number of "clicks" the mouse wheel was rotated.

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

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

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

48 WindowFocusListener interface Method summary: voidwindowGainedFocus ( 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. 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. voidwindowLostFocus ( 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. 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.


Download ppt "Swing II. Swing II Topics WindowListener interface WindowListener interface Icons Icons Scrollbars Scrollbars The Graphics class The Graphics class Colors."

Similar presentations


Ads by Google