Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 13 – Graphical User Components Part 2

Similar presentations


Presentation on theme: "Chapter 13 – Graphical User Components Part 2"— Presentation transcript:

1 Chapter 13 – Graphical User Components Part 2
Outline Introduction JTextArea Creating a Customized Subclass of JPanel Creating a Self-Contained Subclass of JPanel JSlider Windows Designing Programs that Execute as Applets or Applications Using Menus with Frames Using JPopupMenus Pluggable Look-and-Feel Using JDesktopPane and JInternalFrame Layout Managers BoxLayout Layout Manager CardLayout Layout Manager GridBagLayout Layout Manager GridBagConstraints Constants RELATIVE and REMAINDER (Optional Case Study) Thinking About Objects: Model-View- Controller

2 Chapter 13 – Graphical User Components Part 2
(Optional) Discovering Design Patterns: Design Patterns Used in Packages java.awt and javax.swing Creational Design Patterns Structural Design Patterns Behavioral Design Patterns Conclusion

3 Advanced GUI components
Introduction Advanced GUI components Text areas Sliders Menus Advanced layout managers BoxLayout CardLayout GridBagLayout

4 13.2 JTextArea JTextArea Area for manipulating multiple lines of text
Inherits from JTextComponent

5 TextAreaDemo.java Line 20 Lines 22-29
1 // Fig. 13.1: TextAreaDemo.java 2 // Copying selected text from one text area to another. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class TextAreaDemo extends JFrame { private JTextArea textArea1, textArea2; private JButton copyButton; 14 // set up GUI public TextAreaDemo() { super( "TextArea Demo" ); 19 Box box = Box.createHorizontalBox(); 21 String string = "This is a demo string to\n" + "illustrate copying text\n" + "from one TextArea to \n" + "another TextArea using an\n" + "external event\n"; 26 // set up textArea1 textArea1 = new JTextArea( string, 10, 15 ); box.add( new JScrollPane( textArea1 ) ); 30 // set up copyButton copyButton = new JButton( "Copy >>>" ); copyButton.addActionListener( 34 TextAreaDemo.java Line 20 Lines 22-29 Create Box container for organizing GUI components Populate JTextArea with String, then add to Box

6 TextAreaDemo.java Lines 40-43 Lines 52-53
// anonymous inner class to handle copyButton event new ActionListener() { 37 // set text in textArea2 to selected // text from textArea1 public void actionPerformed( ActionEvent event ) { textArea2.setText( textArea1.getSelectedText() ); } 44 } // end anonymous inner class 46 ); // end call to addActionListener 48 box.add( copyButton ); 50 // set up textArea2 textArea2 = new JTextArea( 10, 15 ); textArea2.setEditable( false ); box.add( new JScrollPane( textArea2 ) ); 55 // add box to content pane Container container = getContentPane(); container.add( box ); // place in BorderLayout.CENTER 59 setSize( 425, 200 ); setVisible( true ); } 63 // execute application public static void main( String args[] ) { TextAreaDemo application = new TextAreaDemo(); 68 TextAreaDemo.java Lines Lines 52-53 When user presses JButton, textArea1’s highlighted text is copied into textArea2 Instantiate uneditable JTextArea

7 TextAreaDemo.java Program Output
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 72 73 } // end class TextAreaDemo TextAreaDemo.java Program Output

8 13.3 Creating a Customized Subclass of JPanel
Extend JPanel to create new components Dedicated drawing area Method paintComponent of class JComponent

9 CustomPanel.java Lines 12 Lines 15-23 Line 29
1 // Fig. 13.2: CustomPanel.java 2 // A customized JPanel class. 3 4 // Java core packages 5 import java.awt.*; 6 7 // Java extension packages 8 import javax.swing.*; 9 10 public class CustomPanel extends JPanel { public final static int CIRCLE = 1, SQUARE = 2; private int shape; 13 // use shape to draw an oval or rectangle public void paintComponent( Graphics g ) { super.paintComponent( g ); 18 if ( shape == CIRCLE ) g.fillOval( 50, 10, 60, 60 ); else if ( shape == SQUARE ) g.fillRect( 50, 10, 60, 60 ); } 24 // set shape value and repaint CustomPanel public void draw( int shapeToDraw ) { shape = shapeToDraw; repaint(); } 31 32 } // end class CustomPanel CustomPanel.java Lines 12 Lines Line 29 Store integer representing shape to draw Override method paintComponent of class JComponent to draw oval or rectangle Method repaint calls method paintComponent

10 CustomPanelTest.java Lines 22-23
1 // Fig. 13.3: CustomPanelTest.java 2 // Using a customized Panel object. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class CustomPanelTest extends JFrame { private JPanel buttonPanel; private CustomPanel myPanel; private JButton circleButton, squareButton; 15 // set up GUI public CustomPanelTest() { super( "CustomPanel Test" ); 20 // create custom drawing area myPanel = new CustomPanel(); myPanel.setBackground( Color.green ); 24 // set up squareButton squareButton = new JButton( "Square" ); squareButton.addActionListener( 28 // anonymous inner class to handle squareButton events new ActionListener() { 31 CustomPanelTest.java Lines 22-23 Instantiate CustomPanel object and set background to green

11 CustomPanelTest.java Lines 33-36 Lines 49-52 Line 60
// draw a square public void actionPerformed( ActionEvent event ) { myPanel.draw( CustomPanel.SQUARE ); } 37 } // end anonymous inner class 39 ); // end call to addActionListener 41 circleButton = new JButton( "Circle" ); circleButton.addActionListener( 44 // anonymous inner class to handle circleButton events new ActionListener() { 47 // draw a circle public void actionPerformed( ActionEvent event ) { myPanel.draw( CustomPanel.CIRCLE ); } 53 } // end anonymous inner class 55 ); // end call to addActionListener 57 // set up panel containing buttons buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, 2 ) ); buttonPanel.add( circleButton ); buttonPanel.add( squareButton ); 63 When user presses squareButton, draw square on CustomPanel CustomPanelTest.java Lines Lines Line 60 When user presses circleButton, draw circle on CustomPanel Use GridLayout to organize buttons

12 CustomPanelTest.java Program Output
// attach button panel & custom drawing area to content pane Container container = getContentPane(); container.add( myPanel, BorderLayout.CENTER ); container.add( buttonPanel, BorderLayout.SOUTH ); 68 setSize( 300, 150 ); setVisible( true ); } 72 // execute application public static void main( String args[] ) { CustomPanelTest application = new CustomPanelTest(); 77 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 81 82 } // end class CustomPanelTest CustomPanelTest.java Program Output

13 13.4 Creating a Self-Contained Subclass of JPanel
Does not support conventional events e.g., events offered by buttons, text areas, etc. Capable of recognizing lower-level events e.g., mouse events, key events, etc. Self-contained panel Listens for its own mouse events

14 SelfContainedPanel.java Line 20 Lines 29-30
1 // Fig. 13.4: SelfContainedPanel.java 2 // A self-contained JPanel class that 3 // handles its own mouse events. 4 package com.deitel.jhtp4.ch13; 5 6 // Java core packages 7 import java.awt.*; 8 import java.awt.event.*; 9 10 // Java extension packages 11 import javax.swing.*; 12 13 public class SelfContainedPanel extends JPanel { private int x1, y1, x2, y2; 15 // set up mouse event handling for SelfContainedPanel public SelfContainedPanel() { // set up mouse listener addMouseListener( 21 // anonymous inner class for mouse pressed and // released event handling new MouseAdapter() { 25 // handle mouse press event public void mousePressed( MouseEvent event ) { x1 = event.getX(); y1 = event.getY(); } 32 SelfContainedPanel.java Line 20 Lines 29-30 Self-contained JPanel listens for MouseEvents Save coordinates where user pressed mouse button

15 SelfContainedPanel.java Lines 36-38 Line 46 Lines 54-56
// handle mouse release event public void mouseReleased( MouseEvent event ) { x2 = event.getX(); y2 = event.getY(); repaint(); } 40 } // end anonymous inner class 42 ); // end call to addMouseListener 44 // set up mouse motion listener addMouseMotionListener( 47 // anonymous inner class to handle mouse drag events new MouseMotionAdapter() { 50 // handle mouse drag event public void mouseDragged( MouseEvent event ) { x2 = event.getX(); y2 = event.getY(); repaint(); } 58 } // end anonymous inner class 60 ); // end call to addMouseMotionListener 62 } // end constructor 64 Save coordinates where user released mouse button, then repaint SelfContainedPanel.java Lines Line 46 Lines 54-56 Self-contained JPanel listens for when mouse moves Save coordinates where user dragged mouse, then repaint

16 SelfContainedPanel.java Lines 76-77
// return preferred width and height of SelfContainedPanel public Dimension getPreferredSize() { return new Dimension( 150, 100 ); } 70 // paint an oval at the specified coordinates public void paintComponent( Graphics g ) { super.paintComponent( g ); 75 g.drawOval( Math.min( x1, x2 ), Math.min( y1, y2 ), Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) ); } 79 80 } // end class SelfContainedPanel SelfContainedPanel.java Lines 76-77 Draw oval

17 SelfContainedPanelTest.java Lines 24-25 Line 32
1 // Fig. 13.5: SelfContainedPanelTest.java 2 // Creating a self-contained subclass of JPanel 3 // that processes its own mouse events. 4 5 // Java core packages 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages 10 import javax.swing.*; 11 12 // Deitel packages 13 import com.deitel.jhtp4.ch13.SelfContainedPanel; 14 15 public class SelfContainedPanelTest extends JFrame { private SelfContainedPanel myPanel; 17 18 // set up GUI and mouse motion event handlers for // application window public SelfContainedPanelTest() { // set up a SelfContainedPanel myPanel = new SelfContainedPanel(); myPanel.setBackground( Color.yellow ); 26 Container container = getContentPane(); container.setLayout( new FlowLayout() ); container.add( myPanel ); 30 // set up mouse motion event handling addMouseMotionListener( 33 // anonymous inner class for mouse motion event handling SelfContainedPanelTest.java Lines Line 32 Instantiate SelfCustomPanel object and set background to yellow Register anonymous-inner-class object to handle mouse motion events

18 SelfContainedPanelTest.java Lines 38-49
new MouseMotionListener() { 36 // handle mouse drag event public void mouseDragged( MouseEvent event ) { setTitle( "Dragging: x=" + event.getX() + "; y=" + event.getY() ); } 43 // handle mouse move event public void mouseMoved( MouseEvent event ) { setTitle( "Moving: x=" + event.getX() + "; y=" + event.getY() ); } 50 } // end anonymous inner class 52 ); // end call to addMouseMotionListener 54 setSize( 300, 200 ); setVisible( true ); } 58 // execute application public static void main( String args[] ) { SelfContainedPanelTest application = new SelfContainedPanelTest(); 64 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 68 69 } // end class SelfContainedPanelTest SelfContainedPanelTest.java Lines 38-49 Display String in title bar indicating x-y coordinate where mouse-motion event occurred

19 SelfContainedPanelTest.java Program Output

20 JSlider JSlider Enable users to select from range of integer values Several features Tick marks (major and minor) Snap-to ticks Block marks Orientation (horizontal and vertical)

21 Fig 13.6 Horizontal JSlider Component
Tick Mark Thumb

22 OvalPanel.java Line 18 Lines 22-28
1 // Fig. 13.7: OvalPanel.java 2 // A customized JPanel class. 3 4 // Java core packages 5 import java.awt.*; 6 7 // Java extension packages 8 import javax.swing.*; 9 10 public class OvalPanel extends JPanel { private int diameter = 10; 12 // draw an oval of the specified diameter public void paintComponent( Graphics g ) { super.paintComponent( g ); 17 g.fillOval( 10, 10, diameter, diameter ); } 20 // validate and set diameter, then repaint public void setDiameter( int newDiameter ) { // if diameter invalid, default to 10 diameter = ( newDiameter >= 0 ? newDiameter : 10 ); 26 repaint(); } 29 // used by layout manager to determine preferred size public Dimension getPreferredSize() { return new Dimension( 200, 200 ); } 35 OvalPanel.java Line 18 Lines 22-28 Draw filled oval of diameter Set diameter, then repaint

23 OvalPanel.java 36 // used by layout manager to determine minimum size
public Dimension getMinimumSize() { return getPreferredSize(); } 41 42 } // end class OvalPanel OvalPanel.java

24 SliderDemo.java Lines 22-23 Lines 26-27 Line 32
1 // Fig. 13.8: SliderDemo.java 2 // Using JSliders to size an oval. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 import javax.swing.event.*; 11 12 public class SliderDemo extends JFrame { private JSlider diameterSlider; private OvalPanel myPanel; 15 // set up GUI public SliderDemo() { super( "Slider Demo" ); 20 // set up OvalPanel myPanel = new OvalPanel(); myPanel.setBackground( Color.yellow ); 24 // set up JSlider to control diameter value diameterSlider = new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 ); diameterSlider.setMajorTickSpacing( 10 ); diameterSlider.setPaintTicks( true ); 30 // register JSlider event listener diameterSlider.addChangeListener( 33 SliderDemo.java Lines Lines Line 32 Instantiate OvalPanel object and set background to yellow Instantiate horizontal JSlider object with min. value of 0, max. value of 200 and initial thumb location at 10 Register anonymous ChangeListener object to handle JSlider events

25 SliderDemo.java Lines 38-41
new ChangeListener() { 36 // handle change in slider value public void stateChanged( ChangeEvent e ) { myPanel.setDiameter( diameterSlider.getValue() ); } 42 } // end anonymous inner class 44 ); // end call to addChangeListener 46 // attach components to content pane Container container = getContentPane(); container.add( diameterSlider, BorderLayout.SOUTH ); container.add( myPanel, BorderLayout.CENTER ); 51 setSize( 220, 270 ); setVisible( true ); } 55 // execute application public static void main( String args[] ) { SliderDemo application = new SliderDemo(); 60 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 64 65 } // end class SliderDemo SliderDemo.java Lines 38-41 When user accesses JSlider, set OvalPanel’s diameter according to JSlider value

26 SliderDemo.java Program Output

27 13.6 Windows JFrame Windows with title bar and border
Subclass of java.awt.Frame Subclass of java.awt.Window Heavyweight component Three operations when user closes window DISPOSE_ON_CLOSE DO_NOTHING_ON_CLOSE HIDE_ON_CLOSE

28 13.7 Designing Programs that Execute as Applets or Applications
Java programs Stand-alone applications JFrame Applets in Web browsers Convert applet to GUI-based application

29 DrawShapes is an applet
1 // Fig. 13.9: DrawShapes.java 2 // Draw random lines, rectangles and ovals 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class DrawShapes extends JApplet { private JButton choices[]; private String names[] = { "Line", "Rectangle", "Oval" }; private JPanel buttonPanel; private DrawPanel drawingPanel; private int width = 300, height = 200; 17 // initialize applet; set up GUI public void init() { // set up DrawPanel drawingPanel = new DrawPanel( width, height ); 23 // create array of buttons choices = new JButton[ names.length ]; 26 // set up panel for buttons buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, choices.length ) ); 31 // set up buttons and register their listeners ButtonHandler handler = new ButtonHandler(); 34 DrawShapes.java Line 11 DrawShapes is an applet

30 DrawShapes.java Line 60 Lines 62 Lines 65-68
for ( int count = 0; count < choices.length; count++ ) { choices[ count ] = new JButton( names[ count ] ); buttonPanel.add( choices[ count ] ); choices[ count ].addActionListener( handler ); } 40 // attach components to content pane Container container = getContentPane(); container.add( buttonPanel, BorderLayout.NORTH ); container.add( drawingPanel, BorderLayout.CENTER ); } 46 // enables application to specify width of drawing area public void setWidth( int newWidth ) { width = ( newWidth >= 0 ? newWidth : 300 ); } 52 // enables application to specify height of drawing area public void setHeight( int newHeight ) { height = ( newHeight >= 0 ? newHeight : 200 ); } 58 // execute applet as an application public static void main( String args[] ) { int width, height; 63 // check for command-line arguments if ( args.length != 2 ) { width = 300; height = 200; } DrawShapes.java Line 60 Lines 62 Lines 65-68 DrawShapes is stand-alone application as well Specify application-window size Determine initial application-window size

31 DrawShapes.java Lines 69-72 Lines 75-76 Lines 78-79 Lines 82-88
else { width = Integer.parseInt( args[ 0 ] ); height = Integer.parseInt( args[ 1 ] ); } 73 // create window in which applet will execute JFrame applicationWindow = new JFrame( "An applet running as an application" ); 77 applicationWindow.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 80 // create one applet instance DrawShapes appletObject = new DrawShapes(); appletObject.setWidth( width ); appletObject.setHeight( height ); 85 // call applet's init and start methods appletObject.init(); appletObject.start(); 89 // attach applet to center of window applicationWindow.getContentPane().add( appletObject ); 92 // set the window's size applicationWindow.setSize( width, height ); 95 // showing the window causes all GUI components // attached to the window to be painted applicationWindow.setVisible( true ); } 100 // private inner class to handle button events private class ButtonHandler implements ActionListener { 103 Use command-line arguments to specify window width and height DrawShapes.java Lines Lines Lines Lines 82-88 Instantiate JFrame to run as stand-alone application Allow for window termination Instantiate and initialize applet if stand-alone application

32 104 // determine button user pressed and set drawing area's
// current choice public void actionPerformed( ActionEvent event ) { for ( int count = 0; count < choices.length; count++ ) 109 if ( event.getSource() == choices[ count ] ) { drawingPanel.setCurrentChoice( count ); break; } } 115 } // end private inner class ButtonHandler 117 118 } // end class DrawShapes 119 120 // subclass of JPanel to allow drawing in a separate area 121 class DrawPanel extends JPanel { private int currentChoice = -1; // don't draw first time private int width = 100, height = 100; 124 // initialize width and height of DrawPanel public DrawPanel( int newWidth, int newHeight ) { width = ( newWidth >= 0 ? newWidth : 100 ); height = ( newHeight >= 0 ? newHeight : 100 ); } 131 // draw line, rectangle or oval based on user's choice public void paintComponent( Graphics g ) { super.paintComponent( g ); 136 DrawShapes.java

33 DrawShapes.java 136 137 switch( currentChoice ) { 138 139 case 0:
g.drawLine( randomX(), randomY(), randomX(), randomY() ); break; 143 case 1: g.drawRect( randomX(), randomY(), randomX(), randomY() ); break; 148 case 2: g.drawOval( randomX(), randomY(), randomX(), randomY() ); break; } 154 } // end method paintComponent 156 // specify current shape choice and repaint public void setCurrentChoice( int choice ) { currentChoice = choice; repaint(); } 163 // pick random x coordinate private int randomX() { return ( int ) ( Math.random() * width ); } 169 DrawShapes.java

34 DrawShapes.java Program Output
// pick random y coordinate private int randomY() { return ( int ) ( Math.random() * height ); } 175 176 } // end class DrawPanel DrawShapes.java Program Output

35 13.8 Using Menus with Frames
Allows for performing actions with cluttering GUI Contained by menu bar JMenuBar Comprised of menu items JMenuItem

36 MenuTest.java Line 27 Line 31
1 // Fig : MenuTest.java 2 // Demonstrating menus 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class MenuTest extends JFrame { private Color colorValues[] = { Color.black, Color.blue, Color.red, Color.green }; 14 private JRadioButtonMenuItem colorItems[], fonts[]; private JCheckBoxMenuItem styleItems[]; private JLabel displayLabel; private ButtonGroup fontGroup, colorGroup; private int style; 20 // set up GUI public MenuTest() { super( "Using JMenus" ); 25 // set up File menu and its menu items JMenu fileMenu = new JMenu( "File" ); fileMenu.setMnemonic( 'F' ); 29 // set up About... menu item JMenuItem aboutItem = new JMenuItem( "About..." ); aboutItem.setMnemonic( 'A' ); 33 aboutItem.addActionListener( 35 MenuTest.java Line 27 Line 31 Instantiate File JMenu Instantiate About… JMenuItem to be placed in fileMenu

37 MenuTest.java Lines 40-45 Line 54 Lines 63-66
// anonymous inner class to handle menu item event new ActionListener() { 38 // display message dialog when user selects About... public void actionPerformed( ActionEvent event ) { JOptionPane.showMessageDialog( MenuTest.this, "This is an example\nof using menus", "About", JOptionPane.PLAIN_MESSAGE ); } 46 } // end anonymous inner class 48 ); // end call to addActionListener 50 fileMenu.add( aboutItem ); 52 // set up Exit menu item JMenuItem exitItem = new JMenuItem( "Exit" ); exitItem.setMnemonic( 'x' ); 56 exitItem.addActionListener( 58 // anonymous inner class to handle exitItem event new ActionListener() { 61 // terminate application when user clicks exitItem public void actionPerformed( ActionEvent event ) { System.exit( 0 ); } 67 } // end anonymous inner class 69 ); // end call to addActionListener MenuTest.java Lines Line 54 Lines 63-66 When user selects About… JMenuItem, display message dialog with appropriate text Instantiate Exit JMenuItem to be placed in fileMenu When user selects Exit JMenuItem, exit system

38 MenuTest.java Line 75 Line 80 Line 86 Lines 89-90
71 fileMenu.add( exitItem ); 73 // create menu bar and attach it to MenuTest window JMenuBar bar = new JMenuBar(); setJMenuBar( bar ); bar.add( fileMenu ); 78 // create Format menu, its submenus and menu items JMenu formatMenu = new JMenu( "Format" ); formatMenu.setMnemonic( 'r' ); 82 // create Color submenu String colors[] = { "Black", "Blue", "Red", "Green" }; 85 JMenu colorMenu = new JMenu( "Color" ); colorMenu.setMnemonic( 'C' ); 88 colorItems = new JRadioButtonMenuItem[ colors.length ]; colorGroup = new ButtonGroup(); ItemHandler itemHandler = new ItemHandler(); 92 // create color radio button menu items for ( int count = 0; count < colors.length; count++ ) { colorItems[ count ] = new JRadioButtonMenuItem( colors[ count ] ); 97 colorMenu.add( colorItems[ count ] ); colorGroup.add( colorItems[ count ] ); 100 colorItems[ count ].addActionListener( itemHandler ); } 103 // select first Color menu item colorItems[ 0 ].setSelected( true ); MenuTest.java Line 75 Line 80 Line 86 Lines 89-90 Instantiate JMenuBar to contain JMenus Instantiate Format JMenu Instantiate Color JMenu (submenu of Format JMenu) Instantiate JRadioButtonMenuItems for Color JMenu and ensure that only one menu item is selected at a time

39 MenuTest.java Line 109 Line 114 Lines 117-118
106 // add format menu to menu bar formatMenu.add( colorMenu ); formatMenu.addSeparator(); 110 // create Font submenu String fontNames[] = { "Serif", "Monospaced", "SansSerif" }; 113 JMenu fontMenu = new JMenu( "Font" ); fontMenu.setMnemonic( 'n' ); 116 fonts = new JRadioButtonMenuItem[ fontNames.length ]; fontGroup = new ButtonGroup(); 119 // create Font radio button menu items for ( int count = 0; count < fonts.length; count++ ) { fonts[ count ] = new JRadioButtonMenuItem( fontNames[ count ] ); 124 fontMenu.add( fonts[ count ] ); fontGroup.add( fonts[ count ] ); 127 fonts[ count ].addActionListener( itemHandler ); } 130 // select first Font menu item fonts[ 0 ].setSelected( true ); 133 fontMenu.addSeparator(); 135 // set up style menu items String styleNames[] = { "Bold", "Italic" }; 138 styleItems = new JCheckBoxMenuItem[ styleNames.length ]; StyleHandler styleHandler = new StyleHandler(); Separator places line between JMenuItems MenuTest.java Line 109 Line 114 Lines Instantiate Font JMenu (submenu of Format JMenu) Instantiate JRadioButtonMenuItems for Font JMenu and ensure that only one menu item is selected at a time

40 MenuTest.java 141 142 // create style checkbox menu items
for ( int count = 0; count < styleNames.length; count++ ) { styleItems[ count ] = new JCheckBoxMenuItem( styleNames[ count ] ); 146 fontMenu.add( styleItems[ count ] ); 148 styleItems[ count ].addItemListener( styleHandler ); } 151 // put Font menu in Format menu formatMenu.add( fontMenu ); 154 // add Format menu to menu bar bar.add( formatMenu ); 157 // set up label to display text displayLabel = new JLabel( "Sample Text", SwingConstants.CENTER ); displayLabel.setForeground( colorValues[ 0 ] ); displayLabel.setFont( new Font( "TimesRoman", Font.PLAIN, 72 ) ); 164 getContentPane().setBackground( Color.cyan ); getContentPane().add( displayLabel, BorderLayout.CENTER ); 167 setSize( 500, 200 ); setVisible( true ); 170 } // end constructor 172 MenuTest.java

41 MenuTest.java Line 186 Lines 189-203 Lines 192 and 200-201
// execute application public static void main( String args[] ) { MenuTest application = new MenuTest(); 177 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 181 // inner class to handle action events from menu items private class ItemHandler implements ActionListener { 184 // process color and font selections public void actionPerformed( ActionEvent event ) { // process color selection for ( int count = 0; count < colorItems.length; count++ ) 190 if ( colorItems[ count ].isSelected() ) { displayLabel.setForeground( colorValues[ count ] ); break; } 195 // process font selection for ( int count = 0; count < fonts.length; count++ ) 198 if ( event.getSource() == fonts[ count ] ) { displayLabel.setFont( new Font( fonts[ count ].getText(), style, 72 ) ); break; } 204 repaint(); } 207 MenuTest.java Line 186 Lines Lines 192 and Invoked when user selects JMenuItem Determine which font or color menu generated event Set font or color of JLabel, respectively

42 MenuTest.java Line 214 Lines 219-224
Invoked when user selects JCheckBoxMenuItem } // end class ItemHandler 209 // inner class to handle item events from check box menu items private class StyleHandler implements ItemListener { 212 // process font style selections public void itemStateChanged( ItemEvent e ) { style = 0; 217 // check for bold selection if ( styleItems[ 0 ].isSelected() ) style += Font.BOLD; 221 // check for italic selection if ( styleItems[ 1 ].isSelected() ) style += Font.ITALIC; 225 displayLabel.setFont( new Font( displayLabel.getFont().getName(), style, 72 ) ); 228 repaint(); } 231 } // end class StyleHandler 233 234 } // end class MenuTest MenuTest.java Line 214 Lines Determine new font style

43 MenuTest.java Program Output

44 Context-sensitive popup menus
Using JPopupMenus Context-sensitive popup menus JPopupMenu Menu generated depending on which component is accessed

45 Instantiate JPopupMenu object
1 // Fig : PopupTest.java 2 // Demonstrating JPopupMenus 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class PopupTest extends JFrame { 12 private JRadioButtonMenuItem items[]; private Color colorValues[] = { Color.blue, Color.yellow, Color.red }; 16 private JPopupMenu popupMenu; 18 // set up GUI public PopupTest() { super( "Using JPopupMenus" ); 23 ItemHandler handler = new ItemHandler(); String colors[] = { "Blue", "Yellow", "Red" }; 26 // set up popup menu and its items ButtonGroup colorGroup = new ButtonGroup(); popupMenu = new JPopupMenu(); items = new JRadioButtonMenuItem[ 3 ]; 31 PopupTest.java Line 29 Instantiate JPopupMenu object

46 PopupTest.java Lines 34-42 Lines 56 and 62
// construct each menu item and add to popup menu; also // enable event handling for each menu item for ( int count = 0; count < items.length; count++ ) { items[ count ] = new JRadioButtonMenuItem( colors[ count ] ); 37 popupMenu.add( items[ count ] ); colorGroup.add( items[ count ] ); 40 items[ count ].addActionListener( handler ); } 43 getContentPane().setBackground( Color.white ); 45 // define a MouseListener for the window that displays // a JPopupMenu when the popup trigger event occurs addMouseListener( 49 // anonymous inner class to handle mouse events new MouseAdapter() { 52 // handle mouse press event public void mousePressed( MouseEvent event ) { checkForTriggerEvent( event ); } 58 // handle mouse release event public void mouseReleased( MouseEvent event ) { checkForTriggerEvent( event ); } 64 PopupTest.java Lines Lines 56 and 62 Create JRadioButtonMenuItem objects to add to JPopupMenu Determine whether popup-trigger event occurred when user presses or releases mouse button

47 PopupTest.java Lines 68-70 Line 94
// determine whether event should trigger popup menu private void checkForTriggerEvent( MouseEvent event ) { if ( event.isPopupTrigger() ) popupMenu.show( event.getComponent(), event.getX(), event.getY() ); } 72 } // end anonymous inner clas 74 ); // end call to addMouseListener 76 setSize( 300, 200 ); setVisible( true ); } 80 // execute application public static void main( String args[] ) { PopupTest application = new PopupTest(); 85 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 89 // private inner class to handle menu item events private class ItemHandler implements ActionListener { 92 // process menu item selections public void actionPerformed( ActionEvent event ) { PopupTest.java Lines Line 94 Show JPopupMenu if popup-trigger occurred Invoked when user selects JRadioButtonMenuItem

48 PopupTest.java Lines 97-103 Program Output
// determine which menu item was selected for ( int i = 0; i < items.length; i++ ) if ( event.getSource() == items[ i ] ) { getContentPane().setBackground( colorValues[ i ] ); repaint(); return; } } 105 } // end private inner class ItemHandler 107 108 } // end class PopupTest PopupTest.java Lines Program Output Determine which JRadioButtonMenuItem was selected, then set window background color

49 13.10 Pluggable Look-and-Feel
Change look-and-feel dynamically e.g., Microsoft Windows look-and-feel to Motif look-and-feel Flexible

50 LookAndFeelDemo.java Line 14
1 // Fig : LookAndFeelDemo.java 2 // Changing the look and feel. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class LookAndFeelDemo extends JFrame { 12 private String strings[] = { "Metal", "Motif", "Windows" }; private UIManager.LookAndFeelInfo looks[]; private JRadioButton radio[]; private ButtonGroup group; private JButton button; private JLabel label; private JComboBox comboBox; 20 // set up GUI public LookAndFeelDemo() { super( "Look and Feel Demo" ); 25 Container container = getContentPane(); 27 // set up panel for NORTH of BorderLayout JPanel northPanel = new JPanel(); northPanel.setLayout( new GridLayout( 3, 1, 0, 5 ) ); 31 // set up label for NORTH panel label = new JLabel( "This is a Metal look-and-feel", SwingConstants.CENTER ); northPanel.add( label ); LookAndFeelDemo.java Line 14 Hold installed look-and-feel information

51 LookAndFeelDemo.java 36 37 // set up button for NORTH panel
button = new JButton( "JButton" ); northPanel.add( button ); 40 // set up combo box for NORTH panel comboBox = new JComboBox( strings ); northPanel.add( comboBox ); 44 // attach NORTH panel to content pane container.add( northPanel, BorderLayout.NORTH ); 47 // create array for radio buttons radio = new JRadioButton[ strings.length ]; 50 // set up panel for SOUTH of BorderLayout JPanel southPanel = new JPanel(); southPanel.setLayout( new GridLayout( 1, radio.length ) ); 55 // set up radio buttons for SOUTH panel group = new ButtonGroup(); ItemHandler handler = new ItemHandler(); 59 for ( int count = 0; count < radio.length; count++ ) { radio[ count ] = new JRadioButton( strings[ count ] ); radio[ count ].addItemListener( handler ); group.add( radio[ count ] ); southPanel.add( radio[ count ] ); } 66 // attach SOUTH panel to content pane container.add( southPanel, BorderLayout.SOUTH ); 69 LookAndFeelDemo.java

52 LookAndFeelDemo.java Lines 84-86
// get installed look-and-feel information looks = UIManager.getInstalledLookAndFeels(); 72 setSize( 300, 200 ); setVisible( true ); 75 radio[ 0 ].setSelected( true ); } 78 // use UIManager to change look-and-feel of GUI private void changeTheLookAndFeel( int value ) { // change look and feel try { UIManager.setLookAndFeel( looks[ value ].getClassName() ); SwingUtilities.updateComponentTreeUI( this ); } 88 // process problems changing look and feel catch ( Exception exception ) { exception.printStackTrace(); } } 94 // execute application public static void main( String args[] ) { LookAndFeelDemo application = new LookAndFeelDemo(); 99 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 103 LookAndFeelDemo.java Lines 84-86 Change look-and-feel

53 104 // private inner class to handle radio button events
private class ItemHandler implements ItemListener { 106 // process user's look-and-feel selection public void itemStateChanged( ItemEvent event ) { for ( int count = 0; count < radio.length; count++ ) 111 if ( radio[ count ].isSelected() ) { label.setText( "This is a " + strings[ count ] + " look-and-feel" ); comboBox.setSelectedIndex( count ); 116 changeTheLookAndFeel( count ); } } 120 } // end private inner class ItemHandler 122 123 } // end class LookAndFeelDemo LookAndFeelDemo.java

54 13.11 Using JDesktopPane and JInternalFrame
Multiple document interface Main (parent) window Child windows Switch freely among documents

55 DesktopTest.java Line 12 Line 34
1 // Fig : DesktopTest.java 2 // Demonstrating JDesktopPane. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class DesktopTest extends JFrame { private JDesktopPane theDesktop; 13 // set up GUI public DesktopTest() { super( "Using a JDesktopPane" ); 18 // create menu bar, menu and menu item JMenuBar bar = new JMenuBar(); JMenu addMenu = new JMenu( "Add" ); JMenuItem newFrame = new JMenuItem( "Internal Frame" ); 23 addMenu.add( newFrame ); bar.add( addMenu ); 26 setJMenuBar( bar ); 28 // set up desktop theDesktop = new JDesktopPane(); getContentPane().add( theDesktop ); 32 // set up listener for newFrame menu item newFrame.addActionListener( 35 DesktopTest.java Line 12 Line 34 Manages JInternalFrame child windows displayed in JDesktopPane Handle event when user selects JMenuItem

56 DesktopTest.java Line 40 Lines 43-44 Lines 48-49 Line 52
// anonymous inner class to handle menu item event new ActionListener() { 38 // display new internal window public void actionPerformed( ActionEvent event ) { 41 // create internal frame JInternalFrame frame = new JInternalFrame( "Internal Frame", true, true, true, true ); 45 // attach panel to internal frame content pane Container container = frame.getContentPane(); MyJPanel panel = new MyJPanel(); container.add( panel, BorderLayout.CENTER ); 50 // set size internal frame to size of its contents frame.pack(); 53 // attach internal frame to desktop and show it theDesktop.add( frame ); frame.setVisible( true ); } 58 } // end anonymous inner class 60 ); // end call to addActionListener 62 setSize( 600, 440 ); setVisible( true ); 65 } // end constructor 67 Invoked when user selects JMenuItem DesktopTest.java Line 40 Lines Lines Line 52 Create JInternalFrame JPanels can be added to JInternalFrames Use preferred size for window

57 DesktopTest.java 68 // execute application
public static void main( String args[] ) { DesktopTest application = new DesktopTest(); 72 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 76 77 } // end class DesktopTest 78 79 // class to display an ImageIcon on a panel 80 class MyJPanel extends JPanel { private ImageIcon imageIcon; 82 // load image public MyJPanel() { imageIcon = new ImageIcon( "jhtp4.png" ); } 88 // display imageIcon on panel public void paintComponent( Graphics g ) { // call superclass paintComponent method super.paintComponent( g ); 94 // display icon imageIcon.paintIcon( this, g, 0, 0 ); } 98 DesktopTest.java

58 DesktopTest.java Program Output
// return image dimensions public Dimension getPreferredSize() { return new Dimension( imageIcon.getIconWidth(), imageIcon.getIconHeight() ); } 105 106 } // end class MyJPanel DesktopTest.java Program Output Internal Frames Minimize Maximize Close Minimized internal frame Position the mouse over any corner of a child window to resize the window (if resizing is allowed).

59 DesktopTest.java Program Output
Maximized Internal Frame DesktopTest.java Program Output

60 13.12 Layout Managers Layout Managers BoxLayout CardLayout
GridBagLayout

61 Fig. 13.14 Additional Layout Managers

62 13.13 BoxLayout Layout Manager
Arranges GUI components Horizontally along x-axis Vertically along y-axis

63 BoxLayoutDemo.java Lines 23-28 Lines 31-32
1 // Fig : BoxLayoutDemo.java 2 // Demonstrating BoxLayout. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class BoxLayoutDemo extends JFrame { 12 // set up GUI public BoxLayoutDemo() { super( "Demostrating BoxLayout" ); final int SIZE = 3; 18 Container container = getContentPane(); container.setLayout( new BorderLayout( 30, 30 ) ); 21 // create Box containers with BoxLayout Box boxes[] = new Box[ 4 ]; 24 boxes[ 0 ] = Box.createHorizontalBox(); boxes[ 1 ] = Box.createVerticalBox(); boxes[ 2 ] = Box.createHorizontalBox(); boxes[ 3 ] = Box.createVerticalBox(); 29 // add buttons to boxes[ 0 ] for ( int count = 0; count < SIZE; count++ ) boxes[ 0 ].add( new JButton( "boxes[0]: " + count ) ); 33 BoxLayoutDemo.java Lines Lines 31-32 Define and populate array of Box containers Add three JButtons to horizontal Box

64 Add three JButtons to vertical Box
// create strut and add buttons to boxes[ 1 ] for ( int count = 0; count < SIZE; count++ ) { boxes[ 1 ].add( Box.createVerticalStrut( 25 ) ); boxes[ 1 ].add( new JButton( "boxes[1]: " + count ) ); } 39 // create horizontal glue and add buttons to boxes[ 2 ] for ( int count = 0; count < SIZE; count++ ) { boxes[ 2 ].add( Box.createHorizontalGlue() ); boxes[ 2 ].add( new JButton( "boxes[2]: " + count ) ); } 45 // create rigid area and add buttons to boxes[ 3 ] for ( int count = 0; count < SIZE; count++ ) { boxes[ 3 ].add( Box.createRigidArea( new Dimension( 12, 8 ) ) ); boxes[ 3 ].add( new JButton( "boxes[3]: " + count ) ); } 52 // create vertical glue and add buttons to panel JPanel panel = new JPanel(); panel.setLayout( new BoxLayout( panel, BoxLayout.Y_AXIS ) ); 57 for ( int count = 0; count < SIZE; count++ ) { panel.add( Box.createGlue() ); panel.add( new JButton( "panel: " + count ) ); } 62 // place panels on frame container.add( boxes[ 0 ], BorderLayout.NORTH ); container.add( boxes[ 1 ], BorderLayout.EAST ); container.add( boxes[ 2 ], BorderLayout.SOUTH ); container.add( boxes[ 3 ], BorderLayout.WEST ); container.add( panel, BorderLayout.CENTER ); Strut guarantees space between components BoxLayoutDemo.java Lines Line 36 Lines Line 42 Lines Line 49 Add three JButtons to horizontal Box Glue guarantees expandable space between components Add three JButtons to vertical Box Rigid area guarantees fixed component size

65 BoxLayoutDemo.java Program Output
69 setSize( 350, 300 ); setVisible( true ); 72 } // end constructor 74 // execute application public static void main( String args[] ) { BoxLayoutDemo application = new BoxLayoutDemo(); 79 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 83 84 } // end class BoxLayoutDemo BoxLayoutDemo.java Program Output

66 BoxLayoutDemo.java Program Output

67 13.14 CardLayout Layout Manager
Arranges components in a “deck” of cards Only top “card” is visible Any card can be placed on top of deck Each card can use its own layout manager

68 CardDeck.java Lines 16-17 Lines 28-29
1 // Fig : CardDeck.java 2 // Demonstrating CardLayout. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class CardDeck extends JFrame implements ActionListener { 12 private CardLayout cardManager; private JPanel deck; private JButton controls[]; private String names[] = { "First card", "Next card", "Previous card", "Last card" }; 18 // set up GUI public CardDeck() { super( "CardLayout " ); 23 Container container = getContentPane(); 25 // create the JPanel with CardLayout deck = new JPanel(); cardManager = new CardLayout(); deck.setLayout( cardManager ); 30 CardDeck.java Lines Lines 28-29 Card names Set CardLayout as layout manager for JPanel deck

69 CardDeck.java Lines 32-36 Lines 39-44 Lines 47-55 Lines 58-66
// set up card1 and add it to JPanel deck JLabel label1 = new JLabel( "card one", SwingConstants.CENTER ); JPanel card1 = new JPanel(); card1.add( label1 ); deck.add( card1, label1.getText() ); // add card to deck 37 // set up card2 and add it to JPanel deck JLabel label2 = new JLabel( "card two", SwingConstants.CENTER ); JPanel card2 = new JPanel(); card2.setBackground( Color.yellow ); card2.add( label2 ); deck.add( card2, label2.getText() ); // add card to deck 45 // set up card3 and add it to JPanel deck JLabel label3 = new JLabel( "card three" ); JPanel card3 = new JPanel(); card3.setLayout( new BorderLayout() ); card3.add( new JButton( "North" ), BorderLayout.NORTH ); card3.add( new JButton( "West" ), BorderLayout.WEST ); card3.add( new JButton( "East" ), BorderLayout.EAST ); card3.add( new JButton( "South" ), BorderLayout.SOUTH ); card3.add( label3, BorderLayout.CENTER ); deck.add( card3, label3.getText() ); // add card to deck 56 // create and layout buttons that will control deck JPanel buttons = new JPanel(); buttons.setLayout( new GridLayout( 2, 2 ) ); controls = new JButton[ names.length ]; 61 for ( int count = 0; count < controls.length; count++ ) { controls[ count ] = new JButton( names[ count ] ); controls[ count ].addActionListener( this ); buttons.add( controls[ count ] ); Create first card as JPanel and add to deck CardDeck.java Lines Lines Lines Lines 58-66 Create second card as JPanel with yellow background and add to deck Create third card as JPanel with BorderLayout and add to deck Create fourth card as JPanel with GridLayout and add to deck

70 Switch card in deck, depending on JButton pressed by user
} 67 // add JPanel deck and JPanel buttons to the applet container.add( buttons, BorderLayout.WEST ); container.add( deck, BorderLayout.EAST ); 71 setSize( 450, 200 ); setVisible( true ); 74 } // end constructor 76 // handle button events by switching cards public void actionPerformed( ActionEvent event ) { // show first card if ( event.getSource() == controls[ 0 ] ) cardManager.first( deck ); 83 // show next card else if ( event.getSource() == controls[ 1 ] ) cardManager.next( deck ); 87 // show previous card else if ( event.getSource() == controls[ 2 ] ) cardManager.previous( deck ); 91 // show last card else if ( event.getSource() == controls[ 3 ] ) cardManager.last( deck ); } 96 CardDeck.java Lines 81-94 Switch card in deck, depending on JButton pressed by user

71 CardDeck.java Program Output
// execute application public static void main( String args[] ) { CardDeck cardDeckDemo = new CardDeck(); 101 cardDeckDemo.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 105 106 } // end class CardDeck CardDeck.java Program Output

72 13.15 GridBagLayout Layout Manager.
Flexible GridBagLayout Components can vary in size Components can occupy multiple rows and columns Components can be added in any order Uses GridBagConstraints Specifies how component is placed in GridBagLayout

73 Fig. 13.17 Designing a GUI that will use GridBagLayout.

74 Fig. 13.18 GridBagConstraints instance variables.

75 Fig. 13.19 GridBagLayout with the weights set to zero.

76 GridBagDemo.java Lines 22-23 Line 26
1 // Fig : GridBagDemo.java 2 // Demonstrating GridBagLayout. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class GridBagDemo extends JFrame { private Container container; private GridBagLayout layout; private GridBagConstraints constraints; 15 // set up GUI public GridBagDemo() { super( "GridBagLayout" ); 20 container = getContentPane(); layout = new GridBagLayout(); container.setLayout( layout ); 24 // instantiate gridbag constraints constraints = new GridBagConstraints(); 27 // create GUI components JTextArea textArea1 = new JTextArea( "TextArea1", 5, 10 ); JTextArea textArea2 = new JTextArea( "TextArea2", 2, 2 ); 31 String names[] = { "Iron", "Steel", "Brass" }; JComboBox comboBox = new JComboBox( names ); 34 GridBagDemo.java Lines Line 26 Set GridBagLayout as layout manager Used to determine component location and size in grid

77 GridBagDemo.java Line 43 Line 44 Line 48 Line 49 Lines 57-60
If user resizes Container, first JTextArea is filled entire allocated area in grid JTextField textField = new JTextField( "TextField" ); JButton button1 = new JButton( "Button 1" ); JButton button2 = new JButton( "Button 2" ); JButton button3 = new JButton( "Button 3" ); 39 // textArea1 // weightx and weighty are both 0: the default // anchor for all components is CENTER: the default constraints.fill = GridBagConstraints.BOTH; addComponent( textArea1, 0, 0, 1, 3 ); 45 // button1 // weightx and weighty are both 0: the default constraints.fill = GridBagConstraints.HORIZONTAL; addComponent( button1, 0, 1, 2, 1 ); 50 // comboBox // weightx and weighty are both 0: the default // fill is HORIZONTAL addComponent( comboBox, 2, 1, 2, 1 ); 55 // button2 constraints.weightx = 1000; // can grow wider constraints.weighty = 1; // can grow taller constraints.fill = GridBagConstraints.BOTH; addComponent( button2, 1, 1, 1, 1 ); 61 // button3 // fill is BOTH constraints.weightx = 0; constraints.weighty = 0; addComponent( button3, 1, 2, 1, 1 ); 67 GridBagDemo.java Line 43 Line 44 Line 48 Line 49 Lines 57-60 First JTextArea spans one row and three columns If user resizes Container, first JButton fills horizontally in grid First JButton spans two rows and one column If user resizes Container, second JButton fills extra space

78 GridBagDemo.java 68 // textField
// weightx and weighty are both 0, fill is BOTH addComponent( textField, 3, 0, 2, 1 ); 71 // textArea2 // weightx and weighty are both 0, fill is BOTH addComponent( textArea2, 3, 2, 1, 1 ); 75 setSize( 300, 150 ); setVisible( true ); } 79 // method to set constraints on private void addComponent( Component component, int row, int column, int width, int height ) { // set gridx and gridy constraints.gridx = column; constraints.gridy = row; 87 // set gridwidth and gridheight constraints.gridwidth = width; constraints.gridheight = height; 91 // set constraints and add component layout.setConstraints( component, constraints ); container.add( component ); } 96 GridBagDemo.java

79 GridBagDemo.java Program Output
// execute application public static void main( String args[] ) { GridBagDemo application = new GridBagDemo(); 101 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 105 106 } // end class GridBagDemo GridBagDemo.java Program Output

80 GridBagDemo.java Program Output

81 13.16 GridBagConstraints Constants RELATIVE and REMAINDER
Used in place of variables gridx and gridy RELATIVE Specifies next-to-last component placement in row or column Component should be placed next to one previously added REMAINDER Specifies component as last component in row or column

82 GridBagDemo2.java Lines 22-23 Line 26
1 // Fig : GridBagDemo2.java 2 // Demonstrating GridBagLayout constants. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 public class GridBagDemo2 extends JFrame { private GridBagLayout layout; private GridBagConstraints constraints; private Container container; 15 // set up GUI public GridBagDemo2() { super( "GridBagLayout" ); 20 container = getContentPane(); layout = new GridBagLayout(); container.setLayout( layout ); 24 // instantiate gridbag constraints constraints = new GridBagConstraints(); 27 // create GUI components String metals[] = { "Copper", "Aluminum", "Silver" }; JComboBox comboBox = new JComboBox( metals ); 31 JTextField textField = new JTextField( "TextField" ); 33 String fonts[] = { "Serif", "Monospaced" }; JList list = new JList( fonts ); GridBagDemo2.java Lines Line 26 Set GridBagLayout as layout manager Used to determine component location and size in grid

83 Specify textField as last (only) component in first row
36 String names[] = { "zero", "one", "two", "three", "four" }; JButton buttons[] = new JButton[ names.length ]; 40 for ( int count = 0; count < buttons.length; count++ ) buttons[ count ] = new JButton( names[ count ] ); 43 // define GUI component constraints // textField constraints.weightx = 1; constraints.weighty = 1; constraints.fill = GridBagConstraints.BOTH; constraints.gridwidth = GridBagConstraints.REMAINDER; addComponent( textField ); 51 // buttons[0] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = 1; addComponent( buttons[ 0 ] ); 55 // buttons[1] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.RELATIVE; addComponent( buttons[ 1 ] ); 59 // buttons[2] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.REMAINDER; addComponent( buttons[ 2 ] ); 63 // comboBox -- weightx is 1: fill is BOTH constraints.weighty = 0; constraints.gridwidth = GridBagConstraints.REMAINDER; addComponent( comboBox ); 68 GridBagDemo2.java Line 49 Lines Lines Lines Lines 65-67 Specify textField as last (only) component in first row Place button[0] as first component in second row Place button[1] right next to button[0] Place button[2] right next to button[1] Specify comboBox as last (only) component in third row

84 GridBagDemo2.java Lines 70-72 Lines 75-76 Lines 79-80
Specify buttons[3] as last (only) component in fourth row // buttons[3] -- weightx is 1: fill is BOTH constraints.weighty = 1; constraints.gridwidth = GridBagConstraints.REMAINDER; addComponent( buttons[ 3 ] ); 73 // buttons[4] -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.RELATIVE; addComponent( buttons[ 4 ] ); 77 // list -- weightx and weighty are 1: fill is BOTH constraints.gridwidth = GridBagConstraints.REMAINDER; addComponent( list ); 81 setSize( 300, 200 ); setVisible( true ); 84 } // end constructor 86 // addComponent is programmer-defined private void addComponent( Component component ) { layout.setConstraints( component, constraints ); container.add( component ); // add component } 93 // execute application public static void main( String args[] ) { GridBagDemo2 application = new GridBagDemo2(); 98 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } 102 103 } // end class GridBagDemo2 GridBagDemo2.java Lines Lines Lines 79-80 Place button[4] as first component in fifth row Specify list as last component in fifth row

85 GridbagDemo2.java Program Output

86 Model-View-Controller
(Optional Case Study) Thinking About Objects: Model-View-Controller Model-View-Controller Architectural pattern for building systems Divide system responsibilities into three parts Model Contains all program data and logic View Visual representation of model Controller Defines system behavior by sending user input to model Step by step User uses controller to change data in model Model then informs view of change View changes visual presentation to reflect change

87 13.17 Thinking About Objects (cont.)
Model-View-Controller in elevator simulation Example User presses First Floor of Second Floor Jbutton Controller adds Person to model Model notifies view of Person’s creation View displays Person on Floor in response to notification

88 Fig. 13.22 Class diagram of the elevator simulation.

89 13.17 Thinking About Objects (cont.)
Component diagram (UML) Models “pieces” (components) used by system e.g., .class file, .java files, images, packages, etc. Notation Components are represented as “plugs” Packages are represented as “folders” Dotted arrows indicate dependencies among components Changing one component requires changing another

90 Fir. 13.23 Component diagram for elevator simulation

91 ElevatorSimulation.java Lines 12-13 Lines 19-21 Line 34
2 // Application with Elevator Model, View, and Controller (MVC) 3 package com.deitel.jhtp4.elevator; 4 5 // Java core packages 6 import java.awt.*; 7 8 // Java extension packages 9 import javax.swing.*; 10 11 // Deitel packages 12 import com.deitel.jhtp4.elevator.model.*; 13 import com.deitel.jhtp4.elevator.view.*; 14 import com.deitel.jhtp4.elevator.controller.*; 15 16 public class ElevatorSimulation extends JFrame { 17 // model, view and controller private ElevatorModel model; private ElevatorView view; private ElevatorController controller; 22 // constructor instantiates model, view, and controller public ElevatorSimulation() { super( "Deitel Elevator Simulation" ); 27 // instantiate model, view and controller model = new ElevatorModel(); view = new ElevatorView(); controller = new ElevatorController( model ); 32 // register View for Model events model.setElevatorModelListener( view ); 35 ElevatorSimulation.java Lines Lines Line 34 Import packages model, view and controller ElevatorSimulation aggregates one instance each of classes ElevatorModel, ElevatorView and ElevatorController Register ElevatorModel as listener for ElevatorView

92 ElevatorSimulation.java Lines 37-38
// add view and controller to ElevatorSimulation getContentPane().add( view, BorderLayout.CENTER ); getContentPane().add( controller, BorderLayout.SOUTH ); 39 } // end ElevatorSimulation constructor 41 // main method starts program public static void main( String args[] ) { // instantiate ElevatorSimulation ElevatorSimulation simulation = new ElevatorSimulation(); simulation.setDefaultCloseOperation( EXIT_ON_CLOSE ); simulation.pack(); simulation.setVisible( true ); } 51 } Add ElevatorView and ElevatorController to ElevatorSimulation ElevatorSimulation.java Lines 37-38

93 Continue design-patterns discussion
(Optional) Discovering Design Patterns: Design Patterns Used in Packages java.awt and javax.swing Continue design-patterns discussion Design patterns associated with Java GUI components GUI components take advantage of design patterns

94 13.18.1 Creational Design Patterns
Factory Method design pattern Suppose we design system that opens image from file Several image formats exist (e.g., GIF, JPEG, etc.) Each image format has different structure Method createImage of class Component creates Image Two Image objects (one for GIF image, one for JPEG image) Method createImage uses parameter to determine proper Image subclass from which to instantiate Image object createImage( "image.gif" ); Returns Image object with GIF data createImage( "image.jpg" ); Returns Image object with JPEG data Method createImage is called a factory method Determines subclass to instantiate object at run time

95 13.18.2 Structural Design Patterns
Adapter design pattern Used with objects with incompatible interfaces Allows these objects to collaborate with each other Object’s interface adapts to another object’s interface Similar to adapter for plug on electrical device European electrical sockets differ from those in United States American plug will not work with European socket Use adapter for plug Class MouseAdapter Objects that generate MouseEvents adapts to objects that handle MouseEvents

96 13.18.2 Structural Design Patterns (cont.)
Bridge design pattern Design class Button for Windows and Macintosh systems Class contains button information (e.g., String label) Subclasses Win32Button and MacButton Contain look-and-feel information Problem with this approach Creating class ImageButton (subclass of Button) Requires creating Win32ImageButton and MacImageButton Solution: Separate abstraction (i.e., Button) from implementation (i.e., Win32Button and MacButton) Button contains reference (bridge) to ButtonPeer Handles platform-specific implementations

97 13.18.2 Structural Design Patterns (cont.)
Composite design pattern Organize components into hierarchical structures Each node represents component All nodes implement same interface Polymorphism ensures clients traverse all nodes uniformly Used by Swing components JPanel is JContainer subclass JPanel object can contain GUI component JPanel remains unaware of component’s specific type

98 Fig. 13.25 Inheritance hierarchy for class JPanel.

99 13.18.3 Behavioral Design Patterns
Chain-of-Responsibility design pattern Determine object that handles message at run time Three-line office-phone system First line handles call If first line is busy, second line handles call If second line is busy, third line handles call Message sent through “chain” Each object in chain decides whether to handle message If unable to handle message, that object sends message to next object in chain Method processEvent of class Button Handles AWTEvent or sends to next object

100 13.18.3 Behavioral Design Patterns (cont.)
Command design pattern Applications provide several ways to perform same task Edit menu with menu items for cutting and copying text Toolbar and popup menus may offer same feature Encapsulate functionality (command) in reusable object e.g., “cut text” functionality Functionality can then be added to menus, toolbars, etc. Developers code functionality only once

101 13.18.3 Behavioral Design Patterns (cont.)
Observer design pattern Design program for viewing bank-account information Class BankStatementData store bank-statement data Class TextDisplay displays data in text format Class BarGraphDisplay displays data in bar-graph format Class PieChartDisplay displays data in pie-chart format BankStatementData (subject) notifies Display classes (observers) to display data when it changes Subject notifies observers when subject changes state Observers act in response to notification Promotes loose coupling Used by class java.util.Observable class java.util.Observer

102 Fig. 13.26 Basis for the Observer design pattern.

103 13.18.3 Behavioral Design Patterns (cont.)
Strategy design pattern Encapsulates algorithm LayoutManagers are strategy objects Classes FlowLayout, BorderLayout, GridLayout, etc. Implement interface LayoutManager Each class uses method addLayoutComponent Each method implementation uses different algorithm FlowLayout adds components left-to-right BorderLayout adds components in five regions GridLayout adds components in specified grid Class Container has LayoutManager reference Use method setLayout Select different layout manager at run time

104 13.18.3 Behavioral Design Patterns (cont.)
Template Method design pattern Objects share single algorithm defined in superclass Consider Fig.13.26 Display objects use same algorithm to acquire and display data Get statements from BankStatementData Parse statements Display statements Create superclass BankStatementDisplay Provides methods that comprise algorithm Subclasses override “display” method, because each subclass displays data differently


Download ppt "Chapter 13 – Graphical User Components Part 2"

Similar presentations


Ads by Google