Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 14 l Menus l Making GUIs Pretty (and More Functional) l Box.

Similar presentations


Presentation on theme: "Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 14 l Menus l Making GUIs Pretty (and More Functional) l Box."— Presentation transcript:

1 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 14 l Menus l Making GUIs Pretty (and More Functional) l Box Containers and Box Layout Managers l More on Events and Listeners l Another Look at the Swing Class Hierarchy More Swing Objects

2 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Menus l Three Swing classes used to put a menu in a program: »JMenuBar »JMenu »JMenuItem l Menu items behave in the same way as buttons AbstractButton JButton JMenu JMenuItem

3 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 3 A GUI with a Menu JMenu memoMenu = new JMenu("Memos"); JMenuItem m; m = new JMenuItem("Save Memo 1"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Save Memo 2"); m.addActionListener(this); memoMenu.add(m);... JMenuBar mBar = new JMenuBar(); mBar.add(memoMenu); setJMenuBar(mBar); Create a menu Create a menu item A menu item uses an action listener the same way a button does.

4 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 4 A GUI with a Menu JMenu memoMenu = new JMenu("Memos"); JMenuItem m; m = new JMenuItem("Save Memo 1"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Save Memo 2"); m.addActionListener(this); memoMenu.add(m);... JMenuBar mBar = new JMenuBar(); mBar.add(memoMenu); setJMenuBar(mBar); Each menu item is added to the menu. The menu is added to the menu bar. One way to add a menu bar to a JFrame

5 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 5 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MemoGUI extends JFrame implements ActionListener { public static final int WIDTH = 600; public static final int HEIGHT = 300; public static final int LINES = 10; public static final int CHAR_PER_LINE = 40; private JTextArea theText; private String memo1 = "No Memo 1."; private String memo2 = "No Memo 2."; Display 14.1 GUI with a Menu (1/4) Display 14.1 GUI with a Menu (1/4)

6 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 6 public MemoGUI() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("Memo Saver"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JMenu memoMenu = new JMenu("Memos"); JMenuItem m; m = new JMenuItem("Save Memo 1"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Save Memo 2"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Get Memo 1"); m.addActionListener(this); memoMenu.add(m); Display 14.1 GUI with a Menu (2/4) Display 14.1 GUI with a Menu (2/4)

7 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 7 m = new JMenuItem("Get Memo 2"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Clear"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Exit"); m.addActionListener(this); memoMenu.add(m); JMenuBar mBar = new JMenuBar(); mBar.add(memoMenu); setJMenuBar(mBar); JPanel textPanel = new JPanel(); textPanel.setBackground(Color.blue); theText = new JTextArea(LINES, CHAR_PER_LINE); theText.setBackground(Color.white); textPanel.add(theText); contentPane.add(textPanel, BorderLayout.CENTER); } Display 14.1 GUI with a Menu (3/4) Display 14.1 GUI with a Menu (3/4)

8 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 8 public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Save Memo 1")) memo1 = theText.getText(); else if (actionCommand.equals("Save Memo 2")) memo2 = theText.getText(); else if (actionCommand.equals("Clear")) theText.setText(""); else if (actionCommand.equals("Get Memo 1")) theText.setText(memo1); else if (actionCommand.equals("Get Memo 2")) theText.setText(memo2); else if (actionCommand.equals("Exit")) System.exit(0); else theText.setText("Error in memo interface"); } public static void main(String[] args) { MemoGUI gui = new MemoGUI(); gui.setVisible(true); } Display 14.1 GUI with a Menu (4/4) Display 14.1 GUI with a Menu (4/4)

9 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Nested Menus JMenu is a descendant of JMenuItem Every JMenu object is also a JMenuItem A JMenu can be a menu item in another menu l This allows nested menus l Clicking on a nested menu shows the items in the nested menu and allows them to be selected. AbstractButton JButton JMenu JMenuItem

10 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 10 Making GUIs Pretty (and More Functional) l Adding Icons The JScrollPane Class for Scroll Bars l Adding Borders l Changing the Look and Feel

11 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Using Icons l Icons are (small) pictures l Icons may be added to labels, buttons, and menu items. The ImageIcon class can be used to convert a picture to an icon: ImageIcon SmileyFaceIcon = new ImageIcon(“smiley.gif”); The setIcon method can be used to add an icon to a component: JLabel helloLabel = new JLabel(“Hello”); ImageIcon dukeWavingIcon = new ImageIcon(“duke_waving.gif”); helloLabel.setIcon(dukeWavingIcon);

12 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 12 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class IconDemo extends JFrame implements ActionListener { public static final int WIDTH = 400; public static final int HEIGHT = 200; private JTextField message; Display 14.2 Using Icons (1/4) Display 14.2 Using Icons (1/4)

13 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 13 public IconDemo() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("Icon Demonstration"); Container content = getContentPane(); content.setBackground(Color.white); content.setLayout(new BorderLayout()); JLabel niceLabel = new JLabel("Nice day!"); ImageIcon smileyIcon = new ImageIcon("smiley.gif"); niceLabel.setIcon(smileyIcon); content.add(niceLabel, BorderLayout.NORTH); Display 14.2 Using Icons (2/4) Display 14.2 Using Icons (2/4)

14 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 14 JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); JButton helloButton = new JButton("Hello"); ImageIcon dukeWavingIcon = new ImageIcon("duke_waving.gif"); helloButton.setIcon(dukeWavingIcon); helloButton.addActionListener(this); buttonPanel.add(helloButton); JButton byeButton = new JButton("Good bye"); ImageIcon dukeStandingIcon = new ImageIcon("duke_standing.gif"); byeButton.setIcon(dukeStandingIcon); byeButton.addActionListener(this); buttonPanel.add(byeButton); content.add(buttonPanel, BorderLayout.SOUTH); message = new JTextField(30); content.add(message, BorderLayout.CENTER); } Display 14.2 Using Icons (3/4) Display 14.2 Using Icons (3/4)

15 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 15 public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Hello")) message.setText("Glad to meet you!"); else if (e.getActionCommand().equals("Good bye")) message.setText( "OK, click the upper right button. I'll miss you."); else System.out.println("Error in button interface."); } public static void main(String[] args) { IconDemo iconGui = new IconDemo(); iconGui.setVisible(true); } Display 14.2 Using Icons (4/4) Display 14.2 Using Icons (4/4)

16 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Some Methods in the Classes Jbutton and Jlabel (1/3) l public JButton(), public JLabel() - Creates a button or label with no text or icon on it. - You will later use setText and setIcon with the button or menu item. l public JButton(String text) l public JLabel(String text) - Creates a button or label with the text on it. l public JButton(ImageIcon picture) l public JLabel(ImageIcon picture) - Creates a button or label with the icon picture on it. l public JButton(String text, ImageIcon picture) l public JLabel(String text, ImageIcon picture, int horizontalAlignment) - Creates a button or label with both the text and the icon picture on it. - horizontalAlignment is one of the constants SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT, SwingConstants.LEADING, or SwingConstants.TRAILING.

17 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Some Methods in the Classes Jbutton and Jlabel (2/3) l public void setText(String text) - Makes text the only text on the button or label. l public void setIcon(ImageIcon picture) - Makes picture the only icon on the button or label. l public void setMargin(Insets margin) - JButton has the method setMargin, but JLabel does not. - The method setMargin sets the size of the margin around the text and icon in the button. - public void setMargin(new Insets(int top, int left, int bottom, int right)) l public void setPreferredSize( Dimension preferredSize) - Sets the preferred size. The layout manager is not required to use the preferred size. - public void setPreferredSize(new Dimension(int width, int height))

18 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Some Methods in the Classes Jbutton and Jlabel (3/3) l public void setMaximumSize(Dimension maximumSize) - Sets the maximum size. - public void setMaximumSize(new Dimension(int width, int height)) l public void setMinimumSize(Dimension minimumSize) - Sets the minimum size. - public void setMinimumSize(new Dimension(int width, int height)) l public void setVerticalTextPosition(int textPosition) - Sets the vertical position of the text relative to the icon. - The textPosition should be one of the constants SwingConstants.TOP, SwingConstants.CENTER or SwingConstants.BOTTOM. l public void setHorizontalTextPosition(int textPosition) - Sets the horizontal position of the text relative to the icon. - The textPosition should be one of the constants SwingConstants.RIGHT, SwingConstants.LEFT, SwingConstants.CENTER, or SwingConstants.LEADING, SwingConstants.TRAILING.

19 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 19 The JScrollPane Class for Scroll Bars l A view port is used when not all information can be displayed on screen at once. l Scroll bars move a view port around to show different parts of the information. JScrollPane is a class that can provide a view port with scroll bars. An example using JScrollPane with a JTextArea called theText and a JPanel called textPanel : JScrollPane scrolledText = new JScrollPane(theText); textPanel.add(scrolledText);

20 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 20 View Port for A Text Area

21 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Some Methods and Constants in the Class JScrollPane l public JScrollPane(Component objectToBeScrolled) - Creates a new JScrollPane for the objectToBeScrolled. l public void setHorizontalScrollBarPolicy(int policy) - Sets the policy for showing the horizontal scroll bar. - The policy should be one of JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS JScrollPane.HORIZONTAL_SCROLLBAR_NEVER JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED l public void setVerticalScrollBarPolicy(int policy) - Sets the policy for showing the vertical scroll bar. l JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED l JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED - Constants in the class JScrollPane. - The phrase “ AS_NEEDED ” means the scroll bar is only shown when it is needed.

22 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 22 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ScrollBarDemo extends JFrame implements ActionListener { public static final int WIDTH = 600; public static final int HEIGHT = 300; public static final int LINES = 10; public static final int CHAR_PER_LINE = 40; private JTextArea theText; private String memo1 = "No Memo 1."; private String memo2 = "No Memo 2."; Display 14.5 TextArea with Scroll Bars(1/4) Display 14.5 TextArea with Scroll Bars(1/4)

23 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 23 public ScrollBarDemo() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("Scrolling Memo Saver"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JMenu memoMenu = new JMenu("Memos"); JMenuItem m; m = new JMenuItem("Save Memo 1"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Save Memo 2"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Get Memo 1"); m.addActionListener(this); memoMenu.add(m); Display 14.5 TextArea with Scroll Bars(2/4) Display 14.5 TextArea with Scroll Bars(2/4)

24 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 24 m = new JMenuItem("Get Memo 2"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Clear"); m.addActionListener(this); memoMenu.add(m); m = new JMenuItem("Exit"); m.addActionListener(this); memoMenu.add(m); JMenuBar mBar = new JMenuBar(); mBar.add(memoMenu); setJMenuBar(mBar); JPanel textPanel = new JPanel(); textPanel.setBackground(Color.blue); theText = new JTextArea(LINES, CHAR_PER_LINE); theText.setBackground(Color.white); JScrollPane scrolledText = new JScrollPane(theText); scrolledText.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); scrolledText.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); textPanel.add(scrolledText); contentPane.add(textPanel, BorderLayout.CENTER); } Display 14.5 TextArea with Scroll Bars(3/4) Display 14.5 TextArea with Scroll Bars(3/4)

25 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 25 public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Save Memo 1")) memo1 = theText.getText(); else if (actionCommand.equals("Save Memo 2")) memo2 = theText.getText(); else if (actionCommand.equals("Clear")) theText.setText(""); else if (actionCommand.equals("Get Memo 1")) theText.setText(memo1); else if (actionCommand.equals("Get Memo 2")) theText.setText(memo2); else if (actionCommand.equals("Exit")) System.exit(0); else theText.setText("Error in memo interface"); } public static void main(String[] args) { ScrollBarDemo guiMemo = new ScrollBarDemo(); guiMemo.setVisible(true); } Display 14.5 TextArea with Scroll Bars(4/4) Display 14.5 TextArea with Scroll Bars(4/4)

26 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 26 Execution Result of ScrollBarDemo.java

27 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 27 Adding Borders l A border is an area that frames a component. l Swing provides several different types of borders: »BevelBorder —makes component look raised or lowered »EtchedBorder —similar to BevelBorder but can’t set size »EmptyBorder —extra space around the component »LineBorder —colored border of a given thickness »MatteBorder —similar to LineBorder but can adjust thickness on each side of the component l An example of adding a bevel border to a button: testButton.setBorder(new BevelBorder(BevelBorder.LOWERED));

28 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 28 import javax.swing.*; import java.awt.*; import java.awt.event.*; import javax.swing.border.*; public class BorderDemo extends JFrame implements ActionListener { public static final int WIDTH = 400; public static final int HEIGHT = 300; private JTextField name; Display 14.7 Different Borders (1/4) Display 14.7 Different Borders (1/4)

29 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 29 public BorderDemo() { setTitle("Name Tester with Borders"); setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); Container content = getContentPane(); content.setLayout(new GridLayout(2, 1)); JPanel namePanel = new JPanel(); namePanel.setLayout(new BorderLayout()); namePanel.setBackground(Color.white); name = new JTextField(20); //The following border is not as dramatic as others, //but look closely and you will see it. name.setBorder(new EtchedBorder(Color.green, Color.blue)); namePanel.add(name, BorderLayout.SOUTH); JLabel nameLabel = new JLabel("Enter your name here:"); //The following does insert space around the label. //To see the difference, comment out the following line: nameLabel.setBorder(new EmptyBorder(20, 10, 0, 0)); namePanel.add(nameLabel, BorderLayout.CENTER); Display 14.7 Different Borders (2/4) Display 14.7 Different Borders (2/4)

30 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 30 namePanel.setBorder(new LineBorder(Color.black, 10)); content.add(namePanel); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); JButton testButton = new JButton("Test"); testButton.addActionListener(this); testButton.setBorder( new BevelBorder(BevelBorder.LOWERED)); buttonPanel.add(testButton); JButton clearButton = new JButton("Clear"); clearButton.addActionListener(this); clearButton.setBorder( new BevelBorder(BevelBorder.RAISED)); buttonPanel.add(clearButton); buttonPanel.setBorder( new MatteBorder(60, 40, 30, 20, Color.pink)); content.add(buttonPanel); } Display 14.7 Different Borders (3/4) Display 14.7 Different Borders (3/4)

31 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 31 public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Test")) name.setText("A very good name!"); else if (e.getActionCommand().equals("Clear")) name.setText(""); else name.setText("Error in window interface."); } public static void main(String[] args) { BorderDemo w = new BorderDemo(); w.setVisible(true); } Display 14.7 Different Borders (4/4) Display 14.7 Different Borders (4/4)

32 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 32 Execution Result of BorderDemo.java

33 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 33 Changing the Look and Feel l Look and feel refers to the general appearance of the GUI, including: »Shape and exact placement of buttons »Default colors l Three standard choices for look and feel: »Metal—considered the standard Java look and feel »Motif—often considered the standard Unix look and feel »Windows—looks like the windows you get with the Windows operating system l A Macintosh look and feel is also available

34 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 34 Class Names for Three Looks and Feels l Metal - “ javax.swing.plaf.metal.MetalLookAndFeel ” l Motif - “ com.sun.java.swing.plaf.motif.MotifLookAndFeel ” l Windows - “ com.sun.java.swing.plaf.windows. WindowsLookAndFeel ”

35 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 35 An Example of Changing the Look and Feel of a GUI try { UIManager.setLookAndFeel( “com.sun.java.swing.plaf.motif.MotifLookAndFeel”); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { System.out.println( “Could not load the Motif look and feel”); } Fully qualified class name— includes directory path Try and catch necessary because any one of four exceptions could be thrown

36 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 36 import javax.swing.*; import java.awt.*; public class LookNFeelSample extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200; Display 14.11 Looks and Feels (1/3) Display 14.11 Looks and Feels (1/3)

37 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 37 public LookNFeelSample(String lookNFeelClassName, String title) { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle(title); Container content = getContentPane(); content.setLayout(new FlowLayout()); JButton aButton = new JButton("A Button"); content.add(aButton); JLabel aLabel = new JLabel("This is a label."); content.add(aLabel); try { UIManager.setLookAndFeel(lookNFeelClassName); SwingUtilities.updateComponentTreeUI(this); } catch (Exception e) { System.out.println("Look and feel problem."); } Display 14.11 Looks and Feels (2/3) Display 14.11 Looks and Feels (2/3)

38 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 38 public static void main(String[] args) { LookNFeelSample metalGUI = new LookNFeelSample( "javax.swing.plaf.metal.MetalLookAndFeel", "Metal Look and Feel"); metalGUI.setVisible(true); LookNFeelSample motifGUI = new LookNFeelSample( "com.sun.java.swing.plaf.motif.MotifLookAndFeel", "Motif Look and Feel"); motifGUI.setVisible(true); LookNFeelSample windowsGUI = new LookNFeelSample( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel", "Windows Look and Feel"); windowsGUI.setVisible(true); } Display 14.11 Looks and Feels (3/3) Display 14.11 Looks and Feels (3/3)

39 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 39 Execution Result of LookNFeelSample.java

40 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 40 Box Layout Manager l Useful for a single column or single row of components Specify X_AXIS (horizontal) or Y_AXIS (vertical) layout as second parameter to constructor for layout manager l Provides a means of separating components in a row or column »Strut—allocates a fixed amount of space between two components »Glue—allocates a variable amount of space between two components A Box container is a container that is automatically given a BoxLayout manager.

41 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 41 Box Layout Versus Other Layouts l Horizontal box layout is similar to flow layout. l Vertical box layout is similar to grid layout with only one column. l Big advantage of box layout is control over spacing using struts and glue. l Note that struts and glue should not be used with other layout managers.

42 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 42 Box Layout Demo Program JPanel horizontalPanel = new JPanel(); horizontalPanel.setLayout( new BoxLayout(horizontalPanel, BoxLayout.X_AXIS)); Component horizontalStrut = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalPanel.add(horizontalStrut); JButton hStopButton = new JButton("Red"); hStopButton.addActionListener(this); horizontalPanel.add(hStopButton); Static method in Box class used to create a strut of a particular size for spacing Specifies a horizontal layout

43 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 43 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class BoxLayoutDemo extends Jframe implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static final int HORIZONTAL_STRUT_SIZE = 15; public static final int VERTICAL_STRUT_SIZE = 10; private JPanel colorPanel; Display 14.13 BoxLayout (1/5) Display 14.13 BoxLayout (1/5)

44 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 44 public BoxLayoutDemo() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("Box Demonstration"); Container content = getContentPane(); content.setLayout(new BorderLayout()); colorPanel = new JPanel(); colorPanel.setBackground(Color.blue); content.add(colorPanel, BorderLayout.CENTER); //Horizontal buttons at bottom of frame: JPanel horizontalPanel = new JPanel(); horizontalPanel.setLayout( new BoxLayout(horizontalPanel, BoxLayout.X_AXIS)); Component horizontalStrut = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalPanel.add(horizontalStrut); Display 14.13 BoxLayout (2/5) Display 14.13 BoxLayout (2/5)

45 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 45 JButton hStopButton = new JButton("Red"); hStopButton.addActionListener(this); horizontalPanel.add(hStopButton); Component horizontalStrut2 = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalPanel.add(horizontalStrut2); JButton hGoButton = new JButton("Green"); hGoButton.addActionListener(this); horizontalPanel.add(hGoButton); content.add(horizontalPanel, BorderLayout.SOUTH); //Vertical buttons on right side of frame: JPanel verticalPanel = new JPanel(); verticalPanel.setLayout( new BoxLayout(verticalPanel, BoxLayout.Y_AXIS)); Component verticalStrut = Box.createVerticalStrut(VERTICAL_STRUT_SIZE); verticalPanel.add(verticalStrut); Display 14.13 BoxLayout (3/5) Display 14.13 BoxLayout (3/5)

46 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 46 JButton vStopButton = new JButton("Red"); vStopButton.addActionListener(this); verticalPanel.add(vStopButton); Component verticalStrut2 = Box.createVerticalStrut(VERTICAL_STRUT_SIZE); verticalPanel.add(verticalStrut2); JButton vGoButton = new JButton("Green"); vGoButton.addActionListener(this); verticalPanel.add(vGoButton); content.add(verticalPanel, BorderLayout.EAST); } Display 14.13 BoxLayout (4/5) Display 14.13 BoxLayout (4/5)

47 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 47 public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red")) colorPanel.setBackground(Color.red); else if (e.getActionCommand().equals("Green")) colorPanel.setBackground(Color.green); else System.out.println("Error in button interface."); } public static void main(String[] args) { BoxLayoutDemo gui = new BoxLayoutDemo(); gui.setVisible(true); } Display 14.13 BoxLayout (5/5) Display 14.13 BoxLayout (5/5)

48 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 48 Execution Result of BoxLayoutDemo.java

49 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 49 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class BoxClassDemo extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static final int HORIZONTAL_STRUT_SIZE = 15; public static final int VERTICAL_STRUT_SIZE = 10; private JPanel colorPanel; Display 14.14 Box Container Class (1/4) Display 14.14 Box Container Class (1/4)

50 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 50 public BoxClassDemo() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("Box Demonstration"); Container content = getContentPane(); content.setLayout(new BorderLayout()); colorPanel = new JPanel(); colorPanel.setBackground(Color.blue); content.add(colorPanel, BorderLayout.CENTER); //Horizontal buttons at bottom of frame: Box horizontalBox = Box.createHorizontalBox(); Component horizontalStrut = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalBox.add(horizontalStrut); JButton hStopButton = new JButton("Red"); hStopButton.addActionListener(this); horizontalBox.add(hStopButton); Component horizontalStrut2 = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE); horizontalBox.add(horizontalStrut2); Display 14.14 Box Container Class (2/4) Display 14.14 Box Container Class (2/4)

51 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 51 JButton hGoButton = new JButton("Green"); hGoButton.addActionListener(this); horizontalBox.add(hGoButton); content.add(horizontalBox, BorderLayout.SOUTH); //Vertical buttons on right side of frame: Box verticalBox = Box.createVerticalBox(); Component verticalStrut = Box.createVerticalStrut(VERTICAL_STRUT_SIZE); verticalBox.add(verticalStrut); JButton vStopButton = new JButton("Red"); vStopButton.addActionListener(this); verticalBox.add(vStopButton); Component verticalStrut2 = Box.createVerticalStrut(VERTICAL_STRUT_SIZE); verticalBox.add(verticalStrut2); JButton vGoButton = new JButton("Green"); vGoButton.addActionListener(this); verticalBox.add(vGoButton); content.add(verticalBox, BorderLayout.EAST); } Display 14.14 Box Container Class (3/4) Display 14.14 Box Container Class (3/4)

52 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 52 public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Red")) colorPanel.setBackground(Color.red); else if (e.getActionCommand().equals("Green")) colorPanel.setBackground(Color.green); else System.out.println("Error in button interface."); } public static void main(String[] args) { BoxClassDemo gui = new BoxClassDemo(); gui.setVisible(true); } Display 14.14 Box Container Class (4/4) Display 14.14 Box Container Class (4/4)

53 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 53 Execution Result of BoxClassDemo.java

54 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 54 Some Methods in the CardLayout Manager Class l public void first(Container theContainer) - Causes the first “card” in theContainer to be displayed. l public void last(Container theContainer) - Causes the last “card” in theContainer to be displayed. l public void next(Container theContainer) - Causes the next “card” in theContainer to be displayed. - The next card is the one that was added after the currently displayed “card” was added. l public void previous(Container theContainer) - Causes the previous “card” in theContainer to be displayed. l public void show(Container theContainer, String cardName) - Displays the “card” that was added with the StringcardName as its name.

55 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 55 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CardLayoutDemo extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; private CardLayout dealer; private JPanel deckPanel; public CardLayoutDemo() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("CardLayout Demonstration"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); deckPanel = new JPanel(); dealer = new CardLayout(); deckPanel.setLayout(dealer); Display 14.15 CardLayout (1/4) Display 14.15 CardLayout (1/4)

56 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 56 JPanel startCardPanel = new JPanel(); startCardPanel.setLayout(new FlowLayout()); startCardPanel.setBackground(Color.lightGray); JLabel startLabel = new JLabel("Hello"); startCardPanel.add(startLabel); deckPanel.add("start", startCardPanel); JPanel greenCardPanel = new JPanel(); greenCardPanel.setLayout(new FlowLayout()); greenCardPanel.setBackground(Color.green); JLabel goLabel = new JLabel("Go"); greenCardPanel.add(goLabel); deckPanel.add("green", greenCardPanel); JPanel redCardPanel = new JPanel(); redCardPanel.setLayout(new FlowLayout()); redCardPanel.setBackground(Color.red); JLabel stopLabel = new JLabel("Stop"); redCardPanel.add(stopLabel); deckPanel.add("red", redCardPanel); contentPane.add(deckPanel, BorderLayout.CENTER); Display 14.15 CardLayout (2/4) Display 14.15 CardLayout (2/4)

57 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 57 JPanel buttonPanel = new JPanel(); buttonPanel.setBackground(Color.white); buttonPanel.setLayout(new FlowLayout()); JButton stopButton = new JButton("Red"); stopButton.addActionListener(this); buttonPanel.add(stopButton); JButton goButton = new JButton("Green"); goButton.addActionListener(this); buttonPanel.add(goButton); JButton resetButton = new JButton("Reset"); resetButton.addActionListener(this); buttonPanel.add(resetButton); contentPane.add(buttonPanel, BorderLayout.SOUTH); dealer.first(deckPanel);//Optional } Display 14.15 CardLayout (3/4) Display 14.15 CardLayout (3/4)

58 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 58 public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Red")) dealer.show(deckPanel, "red"); else if (actionCommand.equals("Green")) dealer.show(deckPanel, "green"); else if (actionCommand.equals("Reset")) dealer.show(deckPanel, "start"); else System.out.println("Error in CardLayout Demo."); } public static void main(String[] args) { CardLayoutDemo demoGui = new CardLayoutDemo(); demoGui.setVisible(true); } Display 14.15 CardLayout (4/4) Display 14.15 CardLayout (4/4)

59 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 59 Execution Result of CardLayoutDemo.java

60 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 60 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class InnerClassDemo extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { InnerClassDemo sampleGUI = new InnerClassDemo(); sampleGUI.setVisible(true); } Display 14.17 Inner Class (1/2) Display 14.17 Inner Class (1/2)

61 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 61 public InnerClassDemo() { setSize(WIDTH, HEIGHT); setTitle("Inner Class Demo"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JLabel label = new JLabel( "Please don't click that button!"); contentPane.add(label, BorderLayout.CENTER); addWindowListener(new InnerDestroyer()); } //An inner class with the same functionality //as the class WindowDestroyer. private class InnerDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { System.exit(0); } Display 14.17 Inner Class (2/2) Display 14.17 Inner Class (2/2)

62 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 62 Execution Result of InnerClassDemo.java

63 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 63 The WindowListener Interface For a class to be a listener for window events, it must implement the WindowListener interface. By implementing the WindowListener interface, a window can be its own listener. l The advantage of making a window its own listener is that it is easy to call methods from the listener since they are in the same object.

64 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 64 The WindowListener Interface Implementation of the WindowListener interface requires these seven methods to be defined: »public void windowOpened(WindowEvent e) »public void windowClosing(WindowEvent e) »public void windowClosed(WindowEvent e) »public void windowIconified(WindowEvent e) »public void windowDeiconified(WindowEvent e) »public void windowActivated(WindowEvent e) »public void windowDeactivated(WindowEvent e) l If a method will be not be used, it should be defined with an empty body WindowAdapter is a class that implements all seven methods of the WindowListener with empty bodies.

65 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 65 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class WindowListenerDemo extends JFrame implements ActionListener, WindowListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { WindowListenerDemo demoWindow = new WindowListenerDemo(); demoWindow.setVisible(true); } public WindowListenerDemo() { setSize(WIDTH, HEIGHT); addWindowListener(this); setTitle("Window Listener Demonstration"); Container content = getContentPane(); content.setBackground(Color.blue); Display 14.19 WindowListener (1/3) Display 14.19 WindowListener (1/3)

66 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 66 content.setLayout(new FlowLayout()); JButton stopButton = new JButton("Red"); stopButton.addActionListener(this); content.add(stopButton); JButton goButton = new JButton("Green"); goButton.addActionListener(this); content.add(goButton); } public void actionPerformed(ActionEvent e) { Container content = getContentPane(); if (e.getActionCommand().equals("Red")) content.setBackground(Color.red); else if (e.getActionCommand().equals("Green")) content.setBackground(Color.green); else System.out.println("Error in WindowListenerDemo."); } Display 14.19 WindowListener (2/3) Display 14.19 WindowListener (2/3)

67 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 67 public void windowOpened(WindowEvent e) {} public void windowClosing(WindowEvent e) { this.dispose(); System.exit(0); } public void windowClosed(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} } Display 14.19 WindowListener (3/3) Display 14.19 WindowListener (3/3)

68 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 68 Execution Result of WindowListenerDemo.java

69 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 69 Programming the Close-Window Button The WindowListener interface can be used to program the close-window button. l If the close-window button is not programmed, by default it will close the window but not exit the program. l For a window that does not close when the close-window button is clicked, use a method call like this: setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE); l The CloseWindowDemo uses this method call l When the close-window button is clicked, the program displays a confirmation dialog instead of closing the window.

70 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 70 CloseWindowDemo Program public CloseWindowDemo() { setSize(WIDTH, HEIGHT); setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new InnerDestroyer()); setTitle("Close Window Demo"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout());... } Prevents window from closing so that user can confirm or cancel before window is closed. Constructor for the CloseWindowDemo class, which inherits from JFrame. Defined on next slide

71 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 71 CloseWindowDemo Program private class InnerDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { ConfirmWindow askWindow = new ConfirmWindow(); askWindow.setVisible(true); } Inherits from WindowAdapter so it does not have to define all seven window event methods. Definition of inner class used as listener for the CloseWindowDemo class. ConfirmWindow closes window and exits program if user confirms close.

72 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 72 CloseWindowDemo Program public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Yes")) System.exit(0); else if (e.getActionCommand().equals("No")) dispose(); //Destroys only the ConfirmWindow. else System.out.println("Error in Confirm Window."); } actionPerformed method from the ConfirmWindow inner class The main window will only be closed if the user clicks the “Yes” button in the ConfirmWindow

73 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 73 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CloseWindowDemo extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200; public static void main(String[] args) { CloseWindowDemo gui = new CloseWindowDemo(); gui.setVisible(true); } public CloseWindowDemo() { setSize(WIDTH, HEIGHT); setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE); addWindowListener(new InnerDestroyer()); setTitle("Close Window Demo"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); JLabel message = new JLabel( "Please don't click that button."); contentPane.add(message, BorderLayout.CENTER); } Display 14.20 CloseWindowDemo (1/4) Display 14.20 CloseWindowDemo (1/4)

74 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 74 //Displays a window that checks if the user wants to exit. private class InnerDestroyer extends WindowAdapter { public void windowClosing(WindowEvent e) { ConfirmWindow askWindow = new ConfirmWindow(); askWindow.setVisible(true); } //Designed to be used with the inner class InnerDestroyer in //the class CloseWindowDemo. Checks if the user wants to exit. private class ConfirmWindow extends JFrame implements ActionListener { public static final int WIDTH = 200; public static final int HEIGHT = 100; Display 14.20 CloseWindowDemo (2/4) Display 14.20 CloseWindowDemo (2/4)

75 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 75 public ConfirmWindow() { setSize(WIDTH, HEIGHT); Container confirmContent = getContentPane(); confirmContent.setBackground(Color.white); confirmContent.setLayout(new BorderLayout()); JLabel msgLabel = new JLabel( "Are you sure you want to exit?"); confirmContent.add(msgLabel, BorderLayout.CENTER); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout()); JButton exitButton = new JButton("Yes"); exitButton.addActionListener(this); buttonPanel.add(exitButton); JButton cancelButton = new JButton("No"); cancelButton.addActionListener(this); buttonPanel.add(cancelButton); confirmContent.add(buttonPanel, BorderLayout.SOUTH); } Display 14.20 CloseWindowDemo (3/4) Display 14.20 CloseWindowDemo (3/4)

76 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 76 public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Yes")) System.exit(0); else if (e.getActionCommand().equals("No")) dispose();//Destroys only the ConfirmWindow. else System.out.println("Error in Confirm Window."); } Display 14.20 CloseWindowDemo (4/4) Display 14.20 CloseWindowDemo (4/4)

77 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 77 Execution Result of CloseWindowDemo.java

78 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 78 Changing Components l A program can add or remove components after a GUI has been displayed, but that is beyond the scope of the book. l Making components visible or not visible gives a similar effect. The setVisible method is used in the VisibleDemo program to make only one of the red and green labels visible at a time. (code on next slide)

79 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 79 Changing Components public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals(“Red”)) { colorPanel.setBackground(Color.red); stopLabel.setVisible(false); goLabel.setVisible(true); validate(); }... } There is similar code for when the Green button is pressed, which turns the background green and hides the go label. The actionPerformed method from the VisibleDemo program Visibility changes won’t occur until the validate method is called.

80 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 80 import javax.swing.*; import java.awt.*; import java.awt.event.*; public class VisibilityDemo extends JFrame implements ActionListener { public static final int WIDTH = 300; public static final int HEIGHT = 200; private JLabel upLabel; private JLabel downLabel; public VisibilityDemo() { setSize(WIDTH, HEIGHT); addWindowListener(new WindowDestroyer()); setTitle("Visibility Demonstration"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); contentPane.setBackground(Color.white); Display 14.21 Invisible Labels (1/3) Display 14.21 Invisible Labels (1/3)

81 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 81 upLabel = new JLabel("Here I am up here!"); contentPane.add(upLabel, BorderLayout.NORTH); upLabel.setVisible(false); downLabel = new JLabel("Here I am down here!"); contentPane.add(downLabel, BorderLayout.SOUTH); downLabel.setVisible(false); JPanel buttonPanel = new JPanel(); buttonPanel.setBackground(Color.white); buttonPanel.setLayout(new FlowLayout()); JButton upButton = new JButton("Up"); upButton.addActionListener(this); buttonPanel.add(upButton); JButton downButton = new JButton("Down"); downButton.addActionListener(this); buttonPanel.add(downButton); contentPane.add(buttonPanel, BorderLayout.CENTER); } Display 14.21 Invisible Labels (2/3) Display 14.21 Invisible Labels (2/3)

82 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 82 public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Up")) { upLabel.setVisible(true); downLabel.setVisible(false); validate(); } else if (e.getActionCommand().equals("Down")) { downLabel.setVisible(true); upLabel.setVisible(false); validate(); } else System.out.println("Error in VisibilityDemo interface."); } public static void main(String[] args) { VisibilityDemo demoGui = new VisibilityDemo(); demoGui.setVisible(true); } Display 14.21 Invisible Labels (3/3) Display 14.21 Invisible Labels (3/3)

83 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 83 Execution Result of VisibilityDemo.java

84 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 84 JComponent JLabelJMenuBar AbstractButton JButton JMenu JMenuItem Swing Class Abstract Class Another Look at the Swing Class Hierarchy All of the basic properties of JButton and JMenuItem are inherited from AbstractButton. JButton and JMenuItem are similar because they are derived from the same abstract class. Since AbstractButton is an abstract class, no objects of that class can be made. The purpose of the AbstractButton class is to provide a place for code that is common to JButton and JMenuItem and avoid repeated code.

85 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 85 JComponent JLabelJMenuBar AbstractButton JButton JMenu JMenuItem Swing Class Abstract Class Another Look at the Swing Class Hierarchy JLabel and JButton inherit from a common ancestor, namely Jcomponent, so they have some similarities. Notice, however, that JLabel and JButton are not derived from the same class, even though they have a common ancestor. The hierarchy reflects the fact that JButton and JMenuItem are more similar than JLabel and JButton. Also notice that JMenu inherits from JMenuItem, so it can be used anywhere a JMenuItem can. This allows nested menus.

86 Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 86 Summary You can add icons to JButtons, JLabels, and JMenuItems. A JMenuBar can be added to a JFrame with the method setJMenuBar or with the usual add method. Both buttons and menu items fire action events and so should have an ActionListener registered with them. You can use the class JScrollPane to add scroll bars to a text area. l You can define a window listener class by having it implement the WindowListener interface. l When you define a GUI using Swing you can specify the look and feel for the GUI. If you want a close-button to do something other than close the window, you must use SetDefaultCloseOperation. If you change the visibility of a component you should use the validate method to update the GUI.


Download ppt "Chapter 14Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 14 l Menus l Making GUIs Pretty (and More Functional) l Box."

Similar presentations


Ads by Google