1 / 86

Chapter 14

Chapter 14. More Swing Objects. Menus Making GUIs Pretty (and More Functional) Box Containers and Box Layout Managers More on Events and Listeners Another Look at the Swing Class Hierarchy. AbstractButton. JMenuItem. JButton. JMenu. Menus.

nedaa
Download Presentation

Chapter 14

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

E N D

Presentation Transcript


  1. Chapter 14 More Swing Objects Menus Making GUIs Pretty (and More Functional) Box Containers and Box Layout Managers More on Events and Listeners Another Look at the Swing Class Hierarchy

  2. AbstractButton JMenuItem JButton JMenu Menus • Three Swing classes used to put a menu in a program: • JMenuBar • JMenu • JMenuItem • Menu items behave in the same way as buttons

  3. A GUI witha 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. A GUI witha 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. Display 14.1 GUI with a Menu (1/4) 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.";

  6. Display 14.1 GUI with a Menu (2/4) 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);

  7. Display 14.1 GUI with a Menu (3/4) 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); }

  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)

  9. AbstractButton JMenuItem JButton JMenu 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 • This allows nested menus • Clicking on a nested menu shows the items in the nested menu and allows them to be selected.

  10. Making GUIs Pretty(and More Functional) • Adding Icons • The JScrollPane Class for Scroll Bars • Adding Borders • Changing the Look and Feel

  11. Using Icons • Icons are (small) pictures • 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. Display 14.2 Using Icons (1/4) 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;

  13. Display 14.2 Using Icons (2/4) 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);

  14. Display 14.2 Using Icons (3/4) 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); }

  15. Display 14.2 Using Icons (4/4) 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); } }

  16. Some Methods in the ClassesJbutton and Jlabel (1/3) • 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. • public JButton(String text) • public JLabel(String text) - Creates a button or label with the text on it. • public JButton(ImageIcon picture) • public JLabel(ImageIcon picture) - Creates a button or label with the icon picture on it. • public JButton(String text, ImageIcon picture) • 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. Some Methods in the ClassesJbutton and Jlabel (2/3) • public void setText(String text) - Makes text the only text on the button or label. • public void setIcon(ImageIcon picture) - Makes picture the only icon on the button or label. • 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)) • 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. Some Methods in the ClassesJbutton and Jlabel (3/3) • public void setMaximumSize(Dimension maximumSize) - Sets the maximum size. - public void setMaximumSize(new Dimension(int width, int height)) • public void setMinimumSize(Dimension minimumSize) - Sets the minimum size. - public void setMinimumSize(new Dimension(int width, int height)) • 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. • 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. The JScrollPane Class for Scroll Bars • A view port is used when not all information can be displayed on screen at once. • 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. View Port for A Text Area

  21. Some Methods and Constantsin the Class JScrollPane • public JScrollPane(Component objectToBeScrolled) - Creates a new JScrollPane for the objectToBeScrolled. • 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 • public void setVerticalScrollBarPolicy(int policy) - Sets the policy for showing the vertical scroll bar. • JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED • 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. Display 14.5 TextArea with Scroll Bars(1/4) 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.";

  23. Display 14.5 TextArea with Scroll Bars(2/4) 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);

  24. Display 14.5 TextArea with Scroll Bars(3/4) 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); }

  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)

  26. Execution Result ofScrollBarDemo.java

  27. testButton.setBorder(new BevelBorder(BevelBorder.LOWERED)); Adding Borders • A border is an area that frames a component. • 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 • An example of adding a bevel border to a button:

  28. Display 14.7 Different Borders (1/4) 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;

  29. Display 14.7 Different Borders (2/4) 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);

  30. Display 14.7 Different Borders (3/4) 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); }

  31. Display 14.7 Different Borders (4/4) 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); } }

  32. Execution Result ofBorderDemo.java

  33. Changing the Look and Feel • Look and feel refers to the general appearance of the GUI, including: • Shape and exact placement of buttons • Default colors • 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 • A Macintosh look and feel is also available

  34. Class Names forThree Looks and Feels • Metal - “javax.swing.plaf.metal.MetalLookAndFeel” • Motif - “com.sun.java.swing.plaf.motif.MotifLookAndFeel” • Windows - “com.sun.java.swing.plaf.windows. WindowsLookAndFeel”

  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. Display 14.11 Looks and Feels (1/3) import javax.swing.*; import java.awt.*; public class LookNFeelSample extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200;

  37. Display 14.11 Looks and Feels (2/3) 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."); } }

  38. Display 14.11 Looks and Feels (3/3) 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); } }

  39. Execution Result ofLookNFeelSample.java

  40. Box Layout Manager • 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 • 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. Box Layout Versus Other Layouts • Horizontal box layout is similar to flow layout. • Vertical box layout is similar to grid layout with only one column. • Big advantage of box layout is control over spacing using struts and glue. • Note that struts and glue should not be used with other layout managers.

  42. Box Layout Demo Program Specifies a horizontal layout 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

  43. Display 14.13 BoxLayout (1/5) 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;

  44. Display 14.13 BoxLayout (2/5) 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);

  45. Display 14.13 BoxLayout (3/5) 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);

  46. Display 14.13 BoxLayout (4/5) 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); }

  47. Display 14.13 BoxLayout (5/5) 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); } }

  48. Execution Result ofBoxLayoutDemo.java

  49. Display 14.14 Box Container Class (1/4) 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;

  50. Display 14.14 Box Container Class (2/4) 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);

More Related