Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 141 More Swing Chapter 14. 2 Objectives learn to add menus, icons, borders, and scroll bars to GUIs learn to use the BoxLayout manager and the.

Similar presentations


Presentation on theme: "Chapter 141 More Swing Chapter 14. 2 Objectives learn to add menus, icons, borders, and scroll bars to GUIs learn to use the BoxLayout manager and the."— Presentation transcript:

1 Chapter 141 More Swing Chapter 14

2 2 Objectives learn to add menus, icons, borders, and scroll bars to GUIs learn to use the BoxLayout manager and the Box class learn about inner classes learn about the WindowListener interface learn how to change GUI components to visible or invisible

3 Chapter 143 Outline Menus Making GUIs Pretty and More Functional More Layout Managers Inner Classes More on Events and Listeners The Swing Class Hierarchy Reconsidered

4 Chapter 144 Menus: Outline Programming Example: A GUI with a Menu Menu Bars, Menus, and Menu Items Nested Menus

5 Chapter 145 Programming Example: A GUI with a Menu class MemoGUI

6 Chapter 146 Programming Example: A GUI with a Menu, cont. class MemoGUI, cont.

7 Chapter 147 Programming Example: A GUI with a Menu, cont.

8 Chapter 148 Menu Bars, Menus, and Menu Items You add menus using three Swing classes: –JMenuBar –JMenu –JMenuItem JMenuItem s are placed in a JMenu, and a JMenu typically is placed in a JMenuBar. By default, an object of class JMenuItem is identified by the string that labels it.

9 Chapter 149 Menu Bars, Menus, and Menu Items, cont. Using method add, you can add as many JMenuItem s as you wish to a menu. –example JMenu_Name.add(JMenu_Item); The menu lists them in the order in which they are added. Listeners are added using JMenu_Item_Name.addActionListener (Action_Listener);

10 Chapter 1410 Menu Bars, Menus, and Menu Items, cont. Method actionPerformed is defined for menu items the same way it is defined for buttons. The menu in our example includes an additional entry labeled Exit.

11 Chapter 1411 Menu Bars A menu bar is a container for a menu. Typically it is placed near the top of a windowing interface. Menus are added to the menu bar using JMenu_Bar_Name.add(JMenu_Name); A menu bar can be added to a JFrame using setJMenuBar(JMenu_Bar_Name);

12 Chapter 1412 Menu Bars, cont. Alternatively, a menu bar can be added to the content pane of a JFrame or other container.

13 Chapter 1413 Setting the Action Command for a Menu Item If you do not wish to use the text for a JMenuItem as the default action command, you can set the action command using Menu_Item_Object.setActionCommand (Action_Command_String);

14 Chapter 1414 Nested Menus Class JMenu descends from class JMenuItem, so every JMenu object is also a JMenuItem object. Thus, a JMenu can be a menu item in another menu, permitting menus to be nested (cascading menus).

15 Chapter 1415 Making GUIs Pretty and More Functional: Outline Adding Icons The JScrollPane Class for Scroll Bars Adding Borders

16 Chapter 1416 Adding Icons Typically, an icon is simply a small picture. Labels, buttons, menu items, and other components can have icons. A label or button can have just a string, just an icon, both, or neither. A picture in almost any standard format can be used as the basis for an icon.

17 Chapter 1417 Converting a Picture to a Swing Icon You use class ImageIcon to convert a picture file to a Swing Icon. –example ImageIcon dukeWavingIcon = new ImageIcon(“duke_waving.gif”); You can use a relative or complete path name to specify the picture file.

18 Chapter 1418 Adding an Icon to a Label and a Button To produce a button with just an icon on it, you use JButton dukeButton = new JButton(dukeWavingIcon); –setActionCommand should be used explicitly to give the button an action command.

19 Chapter 1419 Placing an Icon and a String on a Label (or Button) example JButton helloButton = new JButton(“Hello”); ImageIcon dukeWavingIcon = new ImageIcon(“dukeWaving.gif”); helloButton.setIcon(dukeWavingIcon);

20 Chapter 1420 Placing an Icon and a String on a Label (or Button), cont. class IconDemo

21 Chapter 1421 Placing an Icon and a String on a Label (or Button), cont.

22 Chapter 1422 Some Methods in the Classes JButton and JLabel to create a button or label with no text and no icon public JButton() public JLabel() to create a button or label with text public JButton(String text) public JLabel(String text)

23 Chapter 1423 Some Methods in the Classes JButton and JLabel, cont. to create a button or label with an icon public JButton(ImageIcon Picture) public JLabel(ImageIcon Picture) to create a button or label with both text and an icon public JButton(String text, ImageIcon Picture) public JLabel(String text, ImageIcon Picture)

24 Chapter 1424 Some Methods in the Classes JButton and JLabel, cont. to make text the text on the already created button or label public void setText(String text) to make picture the icon on the already created button or label public void setIcon(ImageIcon picture)

25 Chapter 1425 Some Methods in the Classes JButton and JLabel, cont. to set the size of the margin (in pixels) around the text and icon in the button (but not the label) public void setMargin(Insets margin) or public void setMargin (new Insets(int top, int left, int bottom, int right))

26 Chapter 1426 Some Methods in the Classes JButton and JLabel, cont. to set the preferred size (in pixels) of the button or label public void setPreferredSize( Dimension(preferredSize)) or public void setPreferredSize( new Dimension(int width, int height))

27 Chapter 1427 Some Methods in the Classes JButton and JLabel, cont. to set the maximum size (in pixels) of the button or label public void setMaximumSize( Dimension(maximumSize)) or public void setMaximumSize( new Dimension(int width, int height))

28 Chapter 1428 Some Methods in the Classes JButton and JLabel, cont. to set the minimum size (in pixels) of the button or label public void setMinimumSize( Dimension(minimumSize)) or public void setMinimumSize( new Dimension(int width, int height))

29 Chapter 1429 Some Methods in the Classes JButton and JLabel, cont. to set the vertical position of the text relative to the icon public void setVerticalTextPosition (int textPosition) where textPosition is one of the constants SwingConstants.TOP SwingConstants.CENTER (default) SwingContants.BOTTOM

30 Chapter 1430 Some Methods in the Classes JButton and JLabel, cont. to set the horizontal position of the text relative to the icon public void setHorizontalTextPosition (int textPosition) where textPosition is one of the constants SwingConstants.RIGHT (default) SwingConstants.LEFT SwingConstants.CENTER SwingContants.LEADING SwingConstants.TRAILING

31 Chapter 1431 Resizing Buttons The methods for setting the preferred, maximum, and minimum sizes are only recommendations to the layout manager. An image may be clipped (NOT resized) if the icon is too big.

32 Chapter 1432 Classes Dimension and Inset Objects of classes Dimension and Inset are used with buttons, labels, and other objects. The numbers are in pixels. constructors Insets (int top, int left, int bottom, int right) Dimension(int width, int height)

33 Chapter 1433 Classes Dimension and Inset, cont. examples aButton.setMargin(new Insets (10, 20, 10, 20)); aLabel.setPreferredSize (new Dimension (20, 50));

34 Chapter 1434 The JScrollPane Class for Scroll Bars When you create a text area, you specify the number of lines that are visible and the number of characters per line. –example JTextArea the Text = new JTextArea(10,40;) It might be better not to limit the number of lines and the number of characters per line.

35 Chapter 1435 The JScrollPane Class for Scroll Bars, cont. This can be accommodated using scroll bars along the sides of the “window” or view port that shows only a selected portion of the text. The view port functions as a “cut out” over an unbounded document.

36 Chapter 1436 The JScrollPane Class for Scroll Bars, cont.

37 Chapter 1437 The JScrollPane Class for Scroll Bars, cont. Scroll bars can be provided using class JScrollPane. An object of class JScrollPane is essentially a view port with scroll bars.

38 Chapter 1438 The JScrollPane Class for Scroll Bars, cont. The text area is provided as an argument to the JScrollPane constructor. –example JScrollPane scrolledText = new JScrollPane(theText); A JScrollPane can be added to a container such as a JPanel or a JFrame. –example textPanel.add(scrolledText);

39 Chapter 1439 The JScrollPane Class for Scroll Bars, cont. class ScrollBarDemo

40 Chapter 1440 The JScrollPane Class for Scroll Bars, cont.

41 Chapter 1441 Scroll Bar Policy If you omit the invocation of the methods setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy, the scroll bars will be visible only when you need them.

42 Chapter 1442 Some Methods and Constants in Class JScrollBar to create a new JScrollPane for the objectToBeScrolled public JScrollPane(Component objectToBeScrolled)

43 Chapter 1443 Some Methods and Constants in Class JScrollBar, cont. To set the policy for showing the horizontal scroll bar public void setHorizontalScrollBarPolicy(int policy) where policy is one of JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS JScrollPane.HORIZONTAL_SCROLLBAR_NEVER JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED (default)

44 Chapter 1444 Some Methods and Constants in Class JScrollBar, cont. To set the policy for showing the vertical scroll bar public void setVerticalScrollBarPolicy(int policy) where policy is one of JScrollPane.VERTICAL_SCROLLBAR_ALWAYS JScrollPane.VERTICAL_SCROLLBAR_NEVER JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED (default)

45 Chapter 1445 Adding Borders A border is an area around a component that frames the component. You can add a border to any JComponent. A border can serve two purposes: –to make a component more attractive –to separate the component from other components

46 Chapter 1446 Adding Borders, cont. to use the border classes import javax.swing.border.* to provide a border JComponent.setBorder(Border_Object);

47 Chapter 1447 Adding Borders, cont. class BorderDemo

48 Chapter 1448 Adding Borders, cont.

49 Chapter 1449 Adding Borders, cont. You can place a border around any JComponent such as a JButton, a JLabel, a JPanel, or a JTextField. It is common to use an anonymous border object. –example testButton.setBorder(new BevelBorder(BevelBorder.LOWERED));

50 Chapter 1450 Some Border Classes to create a BevelBorder object public BevelBorder(int bevelType) where bevelType is one of BevelBorder.RAISED BevelBorder.LOWERED

51 Chapter 1451 Some Border Classes, cont. to create an EtchedBorder object public EtchedBorder(int etchType, Color highlight, Color shadow) where etchType is one of EtchedBorder.RAISED EtchedBorder.LOWERED to create an EtchedBorder object public EtchedBorder(Color highlight, Color shadow)

52 Chapter 1452 Some Border Classes, cont. to create an EmptyBorder object public EmptyBorder(int top, int left, int bottom, int right) to create a LineBorder object public LineBorder(Color theColor, int thickness) to create LineBorder object with rounded corners public LineBorder(Color theColor, int thickness, boolean roundedCorners)

53 Chapter 1453 Some Border Classes, cont. to create a MatteBorder object public Matte Border(int top, int left, int bottom, int right, Color theColor) to create a MatteBorder object with an icon public Matte Border(int top, int left, int bottom, int right, ImageIcon theIcon)

54 Chapter 1454 More Layout Managers: Outline The BoxLayout Manager Class Struts and Glue Setting the Spacing Between Components The Box Container Class The CardLayout Manager Class

55 Chapter 1455 The BoxLayout Manager Class The FlowLayout manager can produce a horizontal array, and the GridLayout manager with a single column can produce a vertical array. However, the BoxLayout manager and the Box container class are more powerful. A Box container is a panel-like class that uses the BoxLayout manager.

56 Chapter 1456 The BoxLayout Manager Class, cont.

57 Chapter 1457 The BoxLayout Manager Class, cont. We will consider two different programs that produce this GUI.

58 Chapter 1458 The BoxLayout Manager Class, cont. class BoxLayoutDemo

59 Chapter 1459 The BoxLayout Manager Class, cont. The constructor for the BoxLayout manager expects two arguments. –The first argument is the container for which it is the layout manager. –The second argument is one of two constants BoxLayout.X_AXIS BoxLayout.Y_AXIS

60 Chapter 1460 Struts and Glue Static methods in class Box produce invisible components that can be added to a container. These invisible components add space between visible components. Method createHorizontalStrut creates a strut which is an invisible component with a fixed horizontal size.

61 Chapter 1461 Struts and Glue, cont. A layout manager cannot change the vertical size of a horizontal strut. Method VerticalStrut creates a strut which is an invisible component with a fixed vertical size. A layout manager cannot change the horizontal size of a vertical strut.

62 Chapter 1462 Struts and Glue, cont. Like struts, glue components are invisible components. Unlike struts, glue components are not rigid. They are like wet glue and can be made larger or smaller by the layout manager. Struts and glue are best used with a BoxLayout manager.

63 Chapter 1463 Struts and Glue, cont. Glue components can be horizontal or vertical. to create glue components Component horizontalGlue = Box.createHorizontalGlue(); Component verticalGlue = Box.createVerticalGlue(); to add a glue component, use horizontalBox.add(horizontalGlue);

64 Chapter 1464 Setting the Spacing Between Components Except for the BoxLayout manager, the layout managers we have discussed use the following methods: public void setHgap(int hgap) public void setVgap(int vgap) where hgap and vgap are expressed in pixels. Alternatively, you can separate components using an EmptyBorder with any layout manager.

65 Chapter 1465 The Box Container Class An object of class Box behaves like a panel that has a BoxLayout manager. Instead of the JPanel s used in class BoxLayoutDemo, class BoxClassDemo uses Box containers.

66 Chapter 1466 The Box Container Class Instead of the JPanel s used in class BoxLayoutDemo

67 Chapter 1467 The Box Container Class class BoxClassDemo uses Box containers.

68 Chapter 1468 The Box Container Class, cont. Objects of class Box are created using a static method. to create the horizontalBox object Box horizontalBox = Box.createHorizontalBox(); to create the verticalBox object Box verticalBox = Box.createVerticalBox();

69 Chapter 1469 The Box Container Class, cont. Method setLayout is not used to determine the layout of a Box object. An object of class Box automatically uses the BoxLayout manager.

70 Chapter 1470 The Box Container Class, cont. equivalent statements Box horizontalBox = new Box (BoxLayout.X_AXIS); and Box horizontalBox = Box.createHorizontalBox();

71 Chapter 1471 The Box Container Class, cont. more equivalent statements Box verticalBox = new Box (BoxLayout.Y_AXIS); and Box verticalBox = Box.createVerticalBox();

72 Chapter 1472 The CardLayout Manager Class The CardLayout manager class can add a dynamic element to a Swing GUI. The CardLayout manager class provides a set of views you can change - somewhat like flipping through or selecting from a deck of cards. Any number of views can be added to a container, but only one at a time is viewable.

73 Chapter 1473 The CardLayout Manager Class, cont. Views can be selected in order or randomly.

74 Chapter 1474 The CardLayout Manager Class, cont. class CardLayoutDemo

75 Chapter 1475 The CardLayout Manager Class, cont.

76 Chapter 1476 The CardLayout Manager Class, cont. We did not use an anonymous variable deckPanel.setLayout(new CardLayout()); Instead we used dealer = new CardLayout(); deckPanel.setLayout(dealer); to permit us to change the displayed “card” and to permit us to refer to the CardLayout manager in more than one method.

77 Chapter 1477 The CardLayout Manager Class, cont. The first argument of method add names the component provided as the second argument. example deckPanel.add(“start”, startCardPanel); … deckPanel.add(“green”, greenCardPanel); … deckPanel.add(“red”, redCardPanel);

78 Chapter 1478 The CardLayout Manager Class, cont. Two other methods, first and next, permit you to select a view. examples dealer.first(deckPanel); dealer.next(deckPanel); The container always starts with the first component on view. After the last component, next goes back to the first component.

79 Chapter 1479 Some Methods in the CardLayout Manager Class to display the first “card” in the container public void first (Container theContainer); to display the last “card” in the container public void last (Container theContainer); to display the next card public void next (Container theContainer);

80 Chapter 1480 Some Methods in the CardLayout Manager Class, cont. to display the previous “card” public void previous(Container theContainer); to display the “card” that was added with cardName as its name public void show (Container theContainer, String cardName);

81 Chapter 1481 Inner Classes An inner class is a class defined within another class. Often, inner classes are used as helping classes when programming with Swing. Typically, helping classes are declared private.

82 Chapter 1482 Helping Classes Swing windows typically use class WindowDestroyer to close a window. Class WindowDestroyer can be an inner class.

83 Chapter 1483 Helping Classes, cont. class InnerClassDemo

84 Chapter 1484 Helping Classes, cont.

85 Chapter 1485 Advantages of Inner Classes Because inner classes are defined within an outer class, they can make the outer class self-contained (or more self-contained). The methods in the inner class have access to all the instance variables and methods of the outer class, including the private methods and variables. This increases efficiency.

86 Chapter 1486 Advantages of Inner Classes, cont. Inner classes are used frequently as listeners to handle events fired by the outer class or by a component of the outer class. The name of the inner class is local to the class in which it is defined, making it possible to have another class with the same name defined outside the class in which it is defined.

87 Chapter 1487 Invoking Methods of the Outer Class When there is a method invocation in an inner class, but a method with that name exists only in the outer class, the method of the outer class is invoked (i.e. the calling object is the this of the outer class, not the this of the inner class).

88 Chapter 1488 More on Events and Listeners: Outline The WindowListener Interface More Details on Updating a GUI

89 Chapter 1489 The WindowListener Interface When we placed buttons on a window, we made the window itself the button-listener class. But, when we wanted a window listener to respond to window-closing events, we made a separate window-listener class named WindowDestroyer (or an inner class named InnerDestroyer ).

90 Chapter 1490 The WindowListener Interface, cont. We can make the window itself the window listener. The WindowListener interface makes the window itself the listener just as the ActionListener interface makes a window a button listener.

91 Chapter 1491 The WindowListener Interface, cont. To make class ButtonDemo (pages 37-38) an action listener and a window listener, it would begin public class ButtonDemo extends JFrame implements ActionListener, Window Listener Unfortunately, interface WindowListener requires 7 methods to be implemented.

92 Chapter 1492 The WindowListener Interface, cont. These 7 methods are the first of 10 methods in class WindowAdapter. Nevertheless, window class which is derived from class JFrame and which implements the WindowListener interface makes it easy to call a method in the window class within the window listener class, since they are in the same class.

93 Chapter 1493 Methods in the WindowListener Interface

94 Chapter 1494 A Window Listener class WindowListenerDemo

95 Chapter 1495 A Window Listener, cont.

96 Chapter 1496 Method dispose Because the GUI class is its own window listener this.dispose(); is allowed in method windowClosing. Method dispose is a method in class JFame, and class WindowListenerDemo is derived from class JFrame (so it inherits method dispose ).

97 Chapter 1497 Method dispose, cont. Method dispose releases any resources used by the window. The program does not end when method dispose is invoked.

98 Chapter 1498 WindowListener vs. WindowAdapter WindowAdapter is a convenient variant of WindowListener. WindowAdapter implements interface WindowListener by giving every method an empty body. Any class derived from WindowAdapter does not need to provide those empty definitions.

99 Chapter 1499 WindowListener vs. WindowAdapter, cont. But sometimes, you want a listener class to be derived from class JFrame, which prevents it from being derived from class WindowAdapter. Instead it can implement interface WindowListener.

100 Chapter 14100 Java Tip: Programming the Close-Window Button To program the close-window button of a JFrame to do something other than cause the window to go away or end the program, add setDefaultCloseOperation (WindowConstants.DO_NOTHING_ON_CLOSING); to the constructor.

101 Chapter 14101 Java Tip: Programming the Close-Window Button, cont. class CloseWindowDemo

102 Chapter 14102 Java Tip: Programming the Close-Window Button, cont.

103 Chapter 14103 Java Tip: Programming the Close-Window Button, cont. If you invoke setDefaultCloseOperation, by default the window disappears but the program does not end. Simply reprogramming method windowClosing does not cancel the default action.

104 Chapter 14104 Java Tip: Programming the Close-Window Button, cont. To prevent the window from going away, you must first reset the default action with method setDefaultCloseOperation. Further, the close-window button is reprogrammed by registering the inner class InnerDestroyer as the window listener.

105 Chapter 14105 Java Tip: Programming the Close-Window Button, cont. Class ConfirmWindow is an inner class of class CloseWindowDemo, making class CloseWindowDemo self-contained.

106 Chapter 14106 Java Tip: More About setDefaultCloseOperation constants you can use with method setDefaultCloseOperation –to permit any desired action to be programmed in method windowClosing WindowConstants.DO_NOTHING_ON_CLOSE

107 Chapter 14107 Java Tip: More About setDefaultCloseOperation cont. –to hide the frame after invoking any registered WindowListener objects WindowConstants.HIDE_ON_CLOSE (the default action of setDefaultCloseOperation is not invoked)

108 Chapter 14108 Java Tip: More About setDefaultCloseOperation, cont. –to hide and dispose of the frame after invoking any registered WindowListener objects WindowConstants.DISPOSE_ON_CLOSE –to exit the application using method System.exit JFrame.EXIT_ON_CLOSE

109 Chapter 14109 Java Tip: More About setDefaultCloseOperation, cont. to program most Swing GUIs to have no window listener and still get the correct action for the close-window button setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

110 Chapter 14110 Programmng Example: Components with Changing Visibility class VisibilityDemo

111 Chapter 14111 Programmng Example: Components with Changing Visibility

112 Chapter 14112 Method validate Every container class has a method validate for updating the container. Method validate causes the container to lay out its components again and redisplay them. Some changes, such as adding components or changing visibility require an invocation of method validate.

113 Chapter 14113 More Details on Updating GUIs Most changes to a GUI windowing system are done automatically by the repaint manager. However, a change in the visibility of a component requires an invocation of method validate, as we have discussed. Methods pack and repaint are two other updating methods common in Swing code.

114 Chapter 14114 More Details on Updating GUIs, cont. Method pack causes the window to be resized to an approximation of the “preferred size.” Method repaint repaints the window.

115 Chapter 14115 The Swing Class Hierarchy Reconsidered: Outline Buttons, Menus, and Abstract Buttons Other Swing Classes and Methods

116 Chapter 14116 Buttons, Menus, and Abstract Buttons Class JButton and class JMenuItem both are derived from class AbstractButton, from which all of the basic properties and methods (other than constructors) of class JButton and class JMenuItem are inherited. Class AbstractButton inherits some of these methods from class JComponent.

117 Chapter 14117 Buttons, Menus, and Abstract Buttons

118 Chapter 14118 Buttons, Menus, and Abstract Buttons Because class JMenu is derived from class JMenuItem, a menu is also a menu item, permitting a JMenu to be added to another JMenu to make nest menus possible. Because class JMenuBar is derived from class JComponent, a JMenuBar can be added to a container. –With a suitable layout manager, you can have several JMenuBar s, placed almost anywhere.

119 Chapter 14119 Java Tip: More Constructors for Class JMenuItem to create a menu item with no text or icon (assuming setText or setIcon will be used later) public JMenuItem() to create a menu item with the text on it public JMenuItem(String text) to create a menu item with the icon picture on it public JMenuItem(ImageIcon picture)

120 Chapter 14120 Java Tip: More Constructors for Class JMenuItem, cont. to create a menu item with both the text and the icon picture on it public JMenuItem (String text, ImageIcon picture)

121 Chapter 14121 Other Swing Classes and Methods In Chapter 12 and in this chapter, you have learned a lot about Swing. However, a typically book on Swing is longer than the book for this course, and still doesn’t cover all of Swing. Most of the classes, methods, and facilities that should be in Swing probably are in Swing already.

122 Chapter 14122 Summary You have learned to add menus, icons, borders, and scroll bars to GUIs. You have learned to use the BoxLayout manager and the Box class. You have learned about inner classes. You have learned about the WindowListener interface. You have learned how to change GUI components to visible or invisible.


Download ppt "Chapter 141 More Swing Chapter 14. 2 Objectives learn to add menus, icons, borders, and scroll bars to GUIs learn to use the BoxLayout manager and the."

Similar presentations


Ads by Google