Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Chapter 6 GUI Basics. 2 Objectives F To distinguish simple GUI components. F To describe the Java GUI API hierarchy. F To create user interfaces using.

Similar presentations


Presentation on theme: "1 Chapter 6 GUI Basics. 2 Objectives F To distinguish simple GUI components. F To describe the Java GUI API hierarchy. F To create user interfaces using."— Presentation transcript:

1 1 Chapter 6 GUI Basics

2 2 Objectives F To distinguish simple GUI components. F To describe the Java GUI API hierarchy. F To create user interfaces using frames, panels, and simple UI components. F To understand the role of layout managers. F To use the FlowLayout, GridLayout, and BorderLayout managers to layout components in a container. F To specify colors and fonts using the Color and Font classes. F To use JPanel as subcontainers.

3 3 GUI F a Graphical User Interface (GUI) creates a certain way of interacting with a program. F It is what gives a program its look and feel. F GUI allows users to supply inputs and specify actions. F GUIs are created, including buttons, text fields, labels, and text areas.

4 4 Creating GUI Objects // Create a button with text OK JButton jbtOK = new JButton("OK"); // Create a label with text "Enter your name: " JLabel jlblName = new JLabel("Enter your name: "); // Create a text field with text "Type Name Here" JTextField jtfName = new JTextField("Type Name Here"); // Create a check box with text bold JCheckBox jchkBold = new JCheckBox("Bold"); // Create a radio button with text red JRadioButton jrbRed = new JRadioButton("Red"); // Create a combo box with choices red, green, and blue JComboBox jcboColor = new JComboBox(new String[]{"Red“,"Green", "Blue"}); Button LabelText field Check Box Radio Button Combo Box

5 5 Swing vs. AWT So why do the GUI component classes have a prefix J? Instead of JButton, why not name it simply Button? In fact, there is a class already named Button in the java.awt package. the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). For every platform on which Java runs, the AWT components are automatically mapped to the platform- specific components through their respective agents, known as peers.

6 6 Swing vs. AWT AWT is fine for developing simple graphical user interfaces, but not for developing comprehensive GUI projects. Besides, AWT is prone to platform-specific bugs because its peer-based approach relies heavily on the underlying platform. With the release of Java 2, the AWT user-interface components were replaced by a more robust, versatile, and flexible library known as Swing components.

7 7 GUI Class Hierarchy (Swing)

8 8 Container Classes Container classes can contain other GUI components.

9 9 The helper classes are not subclasses of Component. They are used to describe the properties of GUI components such as graphics context, colors, fonts, and dimension. GUI Helper Classes

10 10 Swing GUI Components

11 11 Components Covered in the Core Version

12 12 Components Covered in the Comprehensive Version

13 13 AWT (Optional)

14 14 Frames F Frame is a window that is not contained inside another window. F Frame is the basis to contain other user interface components in Java GUI applications. F The JFrame class can be used to create windows. F For Swing GUI programs, use JFrame class to create widows.

15 15 JFrame Class

16 16 Creating Frames import javax.swing.*; public class MyFrame { public static void main(String[] args) { JFrame frame = new JFrame("Test Frame"); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); }

17 17 Creating Frames

18 18 Adding Components into a Frame // Add a button into the frame frame.getContentPane().add( new JButton("OK")); Title bar Content pane

19 19 Content Pane Delegation in JDK 1.5 // Add a button into the frame frame.getContentPane().add( new JButton("OK")); Title bar Content pane // Add a button into the frame frame.add( new JButton("OK"));

20 20 import javax.swing.*; public class MyFrameWithComponents { public static void main(String[] args) { JFrame frame = new JFrame("MyFrameWithComponents"); // Add a button into the frame JButton jbtOK = new JButton("OK"); frame.add(jbtOK); frame.setSize(400, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); }

21 21 Add button to Frames

22 22 Layout Managers F Java’s layout managers provide a level of abstraction to automatically map your user interface on all window systems. F The UI components are placed in containers. Each container has a layout manager to arrange the UI components within the container. F Layout managers are set in containers using the setLayout(LayoutManager) method in a container.

23 23 Kinds of Layout Managers F FlowLayout F GridLayout F BorderLayout

24 24 The FlowLayout Class

25 25 FlowLayout Example Write a program that adds three labels and text fields into the content pane of a frame with a FlowLayout manager.

26 26 public class ShowFlowLayout extends JFrame { public ShowFlowLayout() { // Set FlowLayout, aligned left with horizontal gap 10 // and vertical gap 20 between components setLayout(new FlowLayout(FlowLayout.LEFT, 10, 20)); // Add labels and text fields to the frame add(new JLabel("First Name")); add(new JTextField(8)); add(new JLabel("MI")); add(new JTextField(1)); add(new JLabel("Last Name")); add(new JTextField(8)); } /** Main method */ public static void main(String[] args) { ShowFlowLayout frame = new ShowFlowLayout(); frame.setTitle("ShowFlowLayout"); frame.setLocationRelativeTo(null); // New since JDK 1.4 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); }

27 27 The GridLayout Class

28 28 GridLayout Example Rewrite the program in the preceding example using a GridLayout manager instead of a FlowLayout manager to display the labels and text fields.

29 29 import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JFrame; import java.awt.GridLayout; public class ShowGridLayout extends JFrame { public ShowGridLayout() { // Set GridLayout, 3 rows, 2 columns, and gaps 5 between // components horizontally and vertically setLayout(new GridLayout(3, 2, 5, 5)); // Add labels and text fields to the frame add(new JLabel("First Name")); add(new JTextField(8)); add(new JLabel("MI")); add(new JTextField(1)); add(new JLabel("Last Name")); add(new JTextField(8)); } /** Main method */ public static void main(String[] args) { ShowGridLayout frame = new ShowGridLayout(); frame.setTitle("ShowGridLayout"); frame.setLocationRelativeTo(null); // New since JDK 1.4 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 125); frame.setVisible(true); }

30 30 The BorderLayout Manager The BorderLayout manager divides the container into five areas: East, South, West, North, and Center. Components are added to a BorderLayout by using the add method. add(Component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER.

31 31 The BorderLayout Class

32 32 import javax.swing.JButton; import javax.swing.JFrame; import java.awt.BorderLayout; public class ShowBorderLayout extends JFrame { public ShowBorderLayout() { // Set BorderLayout with horizontal gap 5 and vertical gap 10 setLayout(new BorderLayout(5, 10)); // Add buttons to the frame add(new JButton("East"), BorderLayout.EAST); add(new JButton("South"), BorderLayout.SOUTH); add(new JButton("West"), BorderLayout.WEST); add(new JButton("North"), BorderLayout.NORTH); add(new JButton("Center"), BorderLayout.CENTER); } /** Main method */ public static void main(String[] args) { ShowBorderLayout frame = new ShowBorderLayout(); frame.setTitle("ShowBorderLayout"); frame.setLocationRelativeTo(null); // New since JDK 1.4 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setVisible(true); }

33 33 The Color Class You can set colors for GUI components by using the java.awt.Color class. Colors are made of red, green, and blue components, each of which is represented by a byte value that describes its intensity, ranging from 0 (darkest shade) to 255 (lightest shade). This is known as the RGB model. Color c = new Color(r, g, b); r, g, and b specify a color by its red, green, and blue components. Example: Color c = new Color(228, 100, 255);

34 34 Standard Colors Thirteen standard colors (black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow) are defined as constants in java.awt.Color. The standard color names are constants, but they are named as variables with lowercase for the first word and uppercase for the first letters of subsequent words. Thus the color names violate the Java naming convention. Since JDK 1.4, you can also use the new constants: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, and YELLOW.

35 35 Setting Colors You can use the following methods to set the component’s background and foreground colors: setBackground(Color c) setForeground(Color c) Example: jbt.setBackground(Color.yellow); jbt.setForeground(Color.red);

36 36 The Font Class Font myFont = new Font(name, style, size); Example: Font myFont = new Font("SansSerif ", Font.BOLD, 16); Font myFont = new Font("Serif", Font.BOLD+Font.ITALIC, 12); JButton jbtOK = new JButton("OK“); jbtOK.setFont(myFont); Font Names Standard font names that are supported in all platforms are: SansSerif, Serif, Monospaced, Dialog, or DialogInput. Font Style Font.PLAIN (0), Font.BOLD (1), Font.ITALIC (2), and Font.BOLD + Font.ITALIC (3)

37 37 Finding All Available Font Names GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontnames = e.getAvailableFontFamilyNames(); for (int i = 0; i < fontnames.length; i++) System.out.println(fontnames[i]);

38 38 Using Panels as Sub-Containers F Panels act as sub-containers for grouping user interface components. F It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel. F To add a component to JFrame, you actually add it to the content pane of JFrame. To add a component to a panel, you add it directly to the panel using the add method.

39 39 Creating a JPanel You can use new JPanel() to create a panel with a default FlowLayout manager or new JPanel(LayoutManager) to create a panel with the specified layout manager. Use the add(Component) method to add a component to the panel. For example, JPanel p = new JPanel(); p.add(new JButton("OK"));

40 40 Testing Panels Example This example uses panels to organize components. The program creates a user interface for a Microwave oven.

41 41 import java.awt.*; import javax.swing.*; public class TestPanels extends JFrame { public TestPanels() { // Create panel p1 for the buttons and set GridLayout JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(4, 3)); // Add buttons to the panel for (int i = 1; i <= 9; i++) p1.add(new JButton("" + i)); p1.add(new JButton("" + 0)); p1.add(new JButton("Start")); p1.add(new JButton("Stop")); // Create panel p2 to hold a text field and p1 JPanel p2 = new JPanel(new BorderLayout()); p2.add(new JTextField("Time to be displayed here"), BorderLayout.NORTH); p2.add(p1, BorderLayout.CENTER); // Add contents to the frame add(p2, BorderLayout.EAST); add(new JButton("Food to be placed here"), BorderLayout.CENTER); } /** Main method */ public static void main(String[] args) { TestPanels frame = new TestPanels(); frame.setTitle("The Front View of a Microwave Oven"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 250); frame.setVisible(true); }

42 42 Common Features of Swing Components

43 43 Borders You can set a border on any object of the JComponent class. Swing has several types of borders. To create a titled border, use new TitledBorder(String title). To create a line border, use new LineBorder(Color color, int width), where width specifies the thickness of the line. For example, the following code displays a titled border on a panel: JPanel panel = new JPanel(); panel.setBorder(new TitleBorder(“My Panel”));

44 44 Test Swing Common Features Component Properties F font F background F foreground F preferredSize F minimumSize F maximumSize JComponent Properties F toolTipText F border

45 45 import java.awt.*; import javax.swing.*; import javax.swing.border.*; public class TestSwingCommonFeatures extends JFrame { public TestSwingCommonFeatures() { // Create a panel to group three buttons JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2)); JButton jbtLeft = new JButton("Left"); JButton jbtCenter = new JButton("Center"); JButton jbtRight = new JButton("Right"); jbtLeft.setBackground(Color.WHITE); jbtCenter.setForeground(Color.GREEN); jbtRight.setToolTipText("This is the Right button"); p1.add(jbtLeft); p1.add(jbtCenter); p1.add(jbtRight); p1.setBorder(new TitledBorder("Three Buttons")); // Create a font and a line border Font largeFont = new Font("TimesRoman", Font.BOLD, 20); Border lineBorder = new LineBorder(Color.BLACK, 2); // Create a panel to group two labels JPanel p2 = new JPanel(new GridLayout(1, 2, 5, 5)); JLabel jlblRed = new JLabel("Red"); JLabel jlblOrange = new JLabel("Orange"); jlblRed.setForeground(Color.RED); jlblOrange.setForeground(Color.ORANGE); jlblRed.setFont(largeFont); jlblOrange.setFont(largeFont); jlblRed.setBorder(lineBorder); jlblOrange.setBorder(lineBorder); p2.add(jlblRed); p2.add(jlblOrange); p2.setBorder(new TitledBorder("Two Labels")); // Add two panels to the frame setLayout(new GridLayout(2, 1, 5, 5)); add(p1); add(p2); } public static void main(String[] args) { // Create a frame and set its properties JFrame frame = new TestSwingCommonFeatures(); frame.setTitle("TestSwingCommonFeatures"); frame.setSize(300, 150); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

46 46

47 47 Image Icons Java uses the javax.swing.ImageIcon class to represent an icon. An icon is a fixed-size picture; typically it is small and used to decorate components. Images are normally stored in image files. You can use new ImageIcon(filename) to construct an image icon. For example, the following statement creates an icon from an image file us.gif in the image directory under the current class path: ImageIcon icon = new ImageIcon("image/us.gif");

48 48 import javax.swing.*; import java.awt.*; public class TestImageIcon extends JFrame { private ImageIcon usIcon = new ImageIcon("image/us.gif"); private ImageIcon myIcon = new ImageIcon("image/my.jpg"); private ImageIcon frIcon = new ImageIcon("image/fr.gif"); private ImageIcon ukIcon = new ImageIcon("image/uk.gif"); public TestImageIcon() { setLayout(new GridLayout(1, 4, 5, 5)); add(new JLabel(usIcon)); add(new JLabel(myIcon)); add(new JButton(frIcon)); add(new JButton(ukIcon)); } /** Main method */ public static void main(String[] args) { TestImageIcon frame = new TestImageIcon(); frame.setTitle("TestImageIcon"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); }

49 49 Procedural vs. Event-Driven Programming F Procedural programming is executed in procedural order.  In event-driven programming, code is executed upon activation of events.

50 50 Taste of Event-Driven Programming F The example displays a button in the frame. A message is displayed on the console when a button is clicked.

51 51 import java.awt.event.*; import java.awt.*; public class SimpleEventDemo extends JFrame { public SimpleEventDemo() { JButton jbtOK = new JButton("OK"); setLayout(new FlowLayout()); add(jbtOK); ActionListener listener = new OKListener(); jbtOK.addActionListener(listener); } /** Main method */ public static void main(String[] args) { JFrame frame = new SimpleEventDemo(); frame.setTitle("SimpleEventDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(100, 80); frame.setVisible(true); } class OKListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("It is OK"); }

52 52 Events F An event can be defined as a type of signal to the program that something has happened. F The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer.

53 53 Event Classes

54 54 Event Information An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method in the EventObject class. The subclasses of EventObject deal with special types of events, such as button actions, window events, component events, mouse movements, and keystrokes. The following slide lists external user actions, source objects, and event types generated.

55 55 Selected User Actions SourceEvent Type User ActionObjectGenerated Click a button JButtonActionEvent Click a check box JCheckBoxItemEvent, ActionEvent Click a radio button JRadioButtonItemEvent, ActionEvent Press return on a text field JTextFieldActionEvent Select a new item JComboBoxItemEvent, ActionEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc. ComponentMouseEvent Key released, pressed, etc. ComponentKeyEvent

56 56 The Delegation Model

57 57 Internal Function of a Source Component

58 58 The Delegation Model: Example JButton jbt = new JButton("OK"); ActionListener listener = new OKListener(); jbt.addActionListener(listener);

59 59 Selected Event Handlers Event ClassListener InterfaceListener Methods (Handlers) ActionEventActionListeneractionPerformed(ActionEvent) ItemEventItemListeneritemStateChanged(ItemEvent) WindowEventWindowListenerwindowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) ContainerEventContainerListenercomponentAdded(ContainerEvent) componentRemoved(ContainerEvent) MouseEventMouseListenermousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent) KeyEventKeyListenerkeyPressed(KeyEvent) keyReleased(KeyEvent) keyTypeed(KeyEvent)

60 60 java.awt.event.ActionEvent

61 61 Inner Class Listeners A listener class is designed specifically to create a listener object for a GUI component (e.g., a button). It will not be shared by other applications. So, it is appropriate to define the listener class inside the frame class as an inner class.

62 62 Inner Classes Inner class: A class is a member of another class. Advantages: In some applications, you can use an inner class to make programs simple. F An inner class can reference the data and methods defined in the outer class in which it nests, so you do not need to pass the reference of the outer class to the constructor of the inner class.

63 63 Inner Classes, cont.

64 64 Inner Classes (cont.) F Inner classes can make programs simple and concise. F An inner class supports the work of its containing outer class and is compiled into a class named OuterClassName$InnerClassName.class. For example, the inner class InnerClass in OuterClass is compiled into OuterClass$InnerClass.class.

65 65 Inner Classes (cont.) F An inner class can be declared public, protected, or private subject to the same visibility rules applied to a member of the class. F An inner class can be declared static. A static inner class can be accessed using the outer class name. A static inner class cannot access nonstatic members of the outer class

66 66 Revising SimpleEventDemo Using Inner Classes import javax.swing.*; import java.awt.event.*; import java.awt.*; public class SimpleEventDemoInnerClass extends JFrame { public SimpleEventDemoInnerClass() { JButton jbtOK = new JButton("OK"); setLayout(new FlowLayout()); add(jbtOK); ActionListener listener = new OKListener(); jbtOK.addActionListener(listener); } /** Main method */ public static void main(String[] args) { JFrame frame = new SimpleEventDemoInnerClass(); frame.setTitle("SimpleEventDemoInnerClass"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(100, 80); frame.setVisible(true); } private class OKListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("It is OK"); }

67 67 Anonymous Inner Classes F An anonymous inner class must always extend a superclass or implement an interface, but it cannot have an explicit extends or implements clause. F An anonymous inner class must implement all the abstract methods in the superclass or in the interface. F An anonymous inner class always uses the no-arg constructor from its superclass to create an instance. If an anonymous inner class implements an interface, the constructor is Object(). F An anonymous inner class is compiled into a class named OuterClassName$n.class. For example, if the outer class Test has two anonymous inner classes, these two classes are compiled into Test$1.class and Test$2.class.

68 68 Anonymous Inner Classes (cont.) Inner class listeners can be shortened using anonymous inner classes. An anonymous inner class is an inner class without a name. It combines declaring an inner class and creating an instance of the class in one step. An anonymous inner class is declared as follows: new SuperClassName/InterfaceName() { // Implement or override methods in superclass or interface // Other methods if necessary }

69 69 Revising SimpleEventDemo Using Anonymous Inner Classes import javax.swing.*; import java.awt.event.*; import java.awt.*; public class SimpleEventDemoAnonymousInnerClass extends JFrame { public SimpleEventDemoAnonymousInnerClass() { JButton jbtOK = new JButton("OK"); setLayout(new FlowLayout()); add(jbtOK); // Create and register anonymous inner class listener jbtOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("It is OK"); } }); } /** Main method */ public static void main(String[] args) { JFrame frame = new SimpleEventDemoAnonymousInnerClass(); frame.setTitle("SimpleEventDemoAnonymousInnerClass"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(100, 80); frame.setVisible(true); }

70 70 Example: Handling Simple Action Events F Objective: Display two buttons OK and Cancel in the window. A message is displayed on the console to indicate which button is clicked, when a button is clicked.

71 71 Handling Simple Action Events import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TestActionEvent extends JFrame { private JButton jbtOK = new JButton("OK"); private JButton jbtCancel = new JButton("Cancel"); public TestActionEvent() { setLayout(new FlowLayout()); add(jbtOK); add(jbtCancel); jbtOK.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("The " + e.getActionCommand() + " button “ + "is clicked at\n " + new java.util.Date(e.getWhen())); } }); jbtCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("The " + e.getActionCommand() + " button “ + "is clicked at\n " + new java.util.Date(e.getWhen())); } }); } /** Main method */ public static void main(String[] args) { TestActionEvent frame = new TestActionEvent(); frame.setTitle("TestActionEvent"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(100, 80); frame.setVisible(true); }

72 72 Interaction Between Source and Listener 1.jbtOK registers btListener by invoking addActionListener(btListner). 2.jbtCancel registers btListener by invoking addActionListener(btListner). 3.jbtOK invokes btListener’s actionPerformed method to process an ActionEvnet. 4.jbtCancel invokes btListener’s actionPerformed method to process an ActionEvent.

73 73 Example: Handling Window Events  Objective: Demonstrate handling the window events. Any subclass of the Window class can generate the following window events: window opened, closing, closed, activated, deactivated, iconified, and deiconified. This program creates a frame, listens to the window events, and displays a message to indicate the occurring event.

74 74 Handling Window Events import java.awt.event.*; import javax.swing.JFrame; public class TestWindowEvent extends JFrame { public static void main(String[] args) { TestWindowEvent frame = new TestWindowEvent(); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("TestWindowEvent"); frame.setSize(100, 80); frame.setVisible(true); } public TestWindowEvent() { addWindowListener(new WindowListener() { /* Handler for window deiconified event * Invoked when a window is changed from a minimized * to a normal state. */ public void windowDeiconified(WindowEvent event) { System.out.println("Window deiconified"); } /* Handler for window iconified event * Invoked when a window is changed from a normal to a * minimized state. For many platforms, a minimized * window is displayed as the icon specified in the * window's iconImage property. */ public void windowIconified(WindowEvent event) { System.out.println("Window iconified"); } /** * Handler for window activated event * Invoked when the window is set to be the user's * active window, which means the window (or one of its * subcomponents) will receive keyboard events. */ public void windowActivated(WindowEvent event) { System.out.println("Window activated"); } /** * Handler for window deactivated event * Invoked when a window is no longer the user's active * window, which means that keyboard events will no * longer be delivered to the window or its subcomponents. */ public void windowDeactivated(WindowEvent event) { System.out.println("Window deactivated"); } /** * Handler for window opened event * Invoked the first time a window is made visible. */ public void windowOpened(WindowEvent event) { System.out.println("Window opened"); }

75 75 Handling Window Events /** * Handler for window closing event * Invoked when the user attempts to close the window * from the window's system menu. If the program does * not explicitly hide or dispose the window while * processing this event, the window close operation will * be cancelled. */ public void windowClosing(WindowEvent event) { System.out.println("Window closing"); } /** * Handler for window closed event * Invoked when a window has been closed as the result * of calling dispose on the window. */ public void windowClosed(WindowEvent event) { System.out.println("Window closed"); } }); }

76 76 Example: Multiple Listeners for a Single Source F Objective: This example modifies Listing 14.1 to add a new listener for each button. The two buttons OK and Cancel use the frame class as the listener. This example creates a new listener class as an additional listener for the action events on the buttons. When a button is clicked, both listeners respond to the action event.

77 77 Multiple Listeners for a Single Source import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TestMultipleListener extends JFrame { private JButton jbtOK = new JButton("OK"); private JButton jbtCancel = new JButton("Cancel"); public TestMultipleListener() { setLayout(new FlowLayout()); add(jbtOK); add(jbtCancel); // Register the first listeners ActionListener firstListener = new FirstListener(); jbtOK.addActionListener(firstListener); jbtCancel.addActionListener(firstListener); // Register the second listener for buttons ActionListener secondListener = new SecondListener(); jbtOK.addActionListener(secondListener); jbtCancel.addActionListener(secondListener); } /** Main method */ public static void main(String[] args) { TestMultipleListener frame = new TestMultipleListener(); frame.setTitle("TestMultipleListener"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(100, 80); frame.setVisible(true); } private class FirstListener implements ActionListener { /** This method will be invoked when a button is clicked */ public void actionPerformed(ActionEvent e) { System.out.print("First listener: "); if (e.getSource() == jbtOK) { System.out.println("The OK button is clicked"); } else if (e.getSource() == jbtCancel) { System.out.println("The Cancel button is clicked"); } /** The class for the second listener */ private class SecondListener implements ActionListener { /** Handle ActionEvent */ public void actionPerformed(ActionEvent e) { System.out.print("Second listener: "); // A button has an actionCommand property, which is same as the // text of the button by default. if (e.getActionCommand().equals("OK")) { System.out.println("The OK button is clicked"); } else if (e.getActionCommand().equals("Cancel")) { System.out.println("The Cancel button is clicked"); }

78 78 Multiple Listeners for a Single Source

79 79 MouseEvent

80 80 Handling Mouse Events  Java provides two listener interfaces, MouseListener and MouseMotionListener, to handle mouse events.  The MouseListener listens for actions such as when the mouse is pressed, released, entered, exited, or clicked.  The MouseMotionListener listens for actions such as dragging or moving the mouse.

81 81 Handling Mouse Events

82 82 Example: Moving Message Using Mouse Objective: Create a program to display a message in a panel. You can use the mouse to move the message. The message moves as the mouse drags and is always displayed at the mouse point.

83 83 Moving Message Using Mouse import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MoveMessageDemo extends JFrame { public MoveMessageDemo() { // Create a MovableMessagePanel instance for moving a message MovableMessagePanel p = new MovableMessagePanel("Welcome to Java"); // Place the message panel in the frame getContentPane().setLayout(new BorderLayout()); getContentPane().add(p); } /** Main method */ public static void main(String[] args) { MoveMessageDemo frame = new MoveMessageDemo(); frame.setTitle("MoveMessageDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } // Inner class: MovableMessagePanel draws a message static class MovableMessagePanel extends JPanel { private String message = "Welcome to Java"; private int x = 20; private int y = 20; /** Construct a panel to draw string s */ public MovableMessagePanel(String s) { message = s; this.addMouseMotionListener(new MouseMotionAdapter() { /** Handle mouse dragged event */ public void mouseDragged(MouseEvent e) { // Get the new location and repaint the screen x = e.getX(); y = e.getY(); repaint(); } }); } /** Paint the component */ protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(message, x, y); }

84 84 Moving Message Using Mouse

85 85 Example: Handling Complex Mouse Events Objective: Create a program for drawing using a mouse. Draw by dragging with the left mouse button pressed; erase by dragging with the right button pressed.

86 86 Handling Complex Mouse Events import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ScribbleDemo extends JFrame { public ScribbleDemo() { // Create a PaintPanel and add it to the frame add(new ScribblePanel(), BorderLayout.CENTER); } /** Main method */ public static void main(String[] args) { ScribbleDemo frame = new ScribbleDemo(); frame.setTitle("ScribbleDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } // ScribblePanel for scribbling using the mouse class ScribblePanel extends JPanel implements MouseListener, MouseMotionListener { final int CIRCLESIZE = 20; // Circle diameter used for erasing private Point lineStart = new Point(0, 0); // Line start point public ScribblePanel() { // Register listener for the mouse event addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mousePressed(MouseEvent e) { lineStart.move(e.getX(), e.getY()); } public void mouseDragged(MouseEvent e) { // Create a Graphics object for drawing Graphics g = getGraphics(); if (e.isMetaDown()) { // Detect right button pressed // Erase the drawing using an oval g.setColor(getBackground()); g.fillOval(e.getX() - (CIRCLESIZE / 2), e.getY() - (CIRCLESIZE / 2), CIRCLESIZE, CIRCLESIZE); } else { g.setColor(Color.black); g.drawLine(lineStart.x, lineStart.y, e.getX(), e.getY()); } lineStart.move(e.getX(), e.getY()); // Dispose this graphics context g.dispose(); } public void mouseMoved(MouseEvent e) { } }

87 87 Handling Complex Mouse Events

88 88 Handling Keyboard Events  keyPressed(KeyEvent e) Called when a key is pressed.  keyReleased(KeyEvent e) Called when a key is released.  keyTyped(KeyEvent e) Called when a key is pressed and then released. To process a keyboard event, use the following handlers in the KeyListener interface:

89 89 The KeyEvent Class  Methods: getKeyChar() method getKeyCode() method  Keys: Home VK_HOME End VK_END Page Up VK_PGUP Page Down VK_PGDN etc...

90 90 The KeyEvent Class, cont.

91 91 Example: Keyboard Events Demo Objective: Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys.

92 92 Keyboard Events Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeyEventDemo extends JFrame { private KeyboardPanel keyboardPanel = new KeyboardPanel(); /** Initialize UI */ public KeyEventDemo() { // Add the keyboard panel to accept and display user input add(keyboardPanel); // Set focus keyboardPanel.setFocusable(true); } /** Main method */ public static void main(String[] args) { KeyEventDemo frame = new KeyEventDemo(); frame.setTitle("KeyEventDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 300); frame.setVisible(true); } // Inner class: KeyboardPanel for receiving key input static class KeyboardPanel extends JPanel { private int x = 100; private int y = 100; private char keyChar = 'A'; // Default key public KeyboardPanel() { addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_DOWN: y += 10; break; case KeyEvent.VK_UP: y -= 10; break; case KeyEvent.VK_LEFT: x -= 10; break; case KeyEvent.VK_RIGHT: x += 10; break; default: keyChar = e.getKeyChar(); } repaint(); } }); } /** Draw the character */ protected void paintComponent(Graphics g) { super.paintComponent(g); g.setFont(new Font("TimesRoman", Font.PLAIN, 24)); g.drawString(String.valueOf(keyChar), x, y); }

93 93 Keyboard Events Demo

94 94 The Timer Class Some non-GUI components can fire events. The javax.swing.Timer class is a source component that fires an ActionEvent at a predefined rate. Optional The Timer class can be used to control animations. For example, you can use it to display a moving message. AnimationDemo Run

95 95 Animation Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AnimationDemo extends JFrame { public AnimationDemo() { // Create a MovingMessagePanel for displaying a moving message add(new MovingMessagePanel("message moving?")); } /** Main method */ public static void main(String[] args) { AnimationDemo frame = new AnimationDemo(); frame.setTitle("AnimationDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(280, 100); frame.setVisible(true); } // Displaying a moving message static class MovingMessagePanel extends JPanel { private String message = "Welcome to Java"; private int xCoordinate = 0; private int yCoordinate = 20; public MovingMessagePanel(String message) { this.message = message; // Create a timer Timer timer = new Timer(1000, new TimerListener()); timer.start(); } /** Paint message */ public void paintComponent(Graphics g) { super.paintComponent(g); if (xCoordinate > getWidth()) { xCoordinate = -20; } xCoordinate += 5; g.drawString(message, xCoordinate, yCoordinate); } class TimerListener implements ActionListener { /** Handle ActionEvent */ public void actionPerformed(ActionEvent e) { repaint(); }

96 96 Clock Animation In Chapter 12, you drew a StillClock to show the current time. The clock does not tick after it is displayed. What can you do to make the clock display a new current time every second? The key to making the clock tick is to repaint it every second with a new current time. You can use a timer to control how to repaint the clock.

97 97 StillClock import java.awt.*; import javax.swing.*; import java.util.*; public class StillClock extends JPanel { private int hour; private int minute; private int second; /** Construct a default clock with the current time*/ public StillClock() { setCurrentTime(); } /** Construct a clock with specified hour, minute, and second */ public StillClock(int hour, int minute, int second) { this.hour = hour; this.minute = minute; this.second = second; } /** Return hour */ public int getHour() { return hour; } /** Set a new hour */ public void setHour(int hour) { this.hour = hour; repaint(); } /** Return minute */ public int getMinute() { return minute; } /** Set a new minute */ public void setMinute(int minute) { this.minute = minute; repaint(); } /** Return second */ public int getSecond() { return second; } /** Set a new second */ public void setSecond(int second) { this.second = second; repaint(); } /** Draw the clock */ protected void paintComponent(Graphics g) { super.paintComponent(g); // Initialize clock parameters int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5); int xCenter = getWidth() / 2; int yCenter = getHeight() / 2;

98 98 StillClock /** Draw the clock */ protected void paintComponent(Graphics g) { super.paintComponent(g); // Initialize clock parameters int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5); int xCenter = getWidth() / 2; int yCenter = getHeight() / 2; // Draw circle g.setColor(Color.black); g.drawOval(xCenter - clockRadius, yCenter - clockRadius, 2 * clockRadius, 2 * clockRadius); g.drawString("12", xCenter - 5, yCenter - clockRadius + 12); g.drawString("9", xCenter - clockRadius + 3, yCenter + 5); g.drawString("3", xCenter + clockRadius - 10, yCenter + 3); g.drawString("6", xCenter - 3, yCenter + clockRadius - 3); // Draw second hand int sLength = (int)(clockRadius * 0.8); int xSecond = (int)(xCenter + sLength * Math.sin(second * (2 * Math.PI / 60))); int ySecond = (int)(yCenter - sLength * Math.cos(second * (2 * Math.PI / 60))); g.setColor(Color.red); g.drawLine(xCenter, yCenter, xSecond, ySecond); // Draw minute hand int mLength = (int)(clockRadius * 0.65); int xMinute = (int)(xCenter + mLength * Math.sin(minute * (2 * Math.PI / 60))); int yMinute = (int)(yCenter - mLength * Math.cos(minute * (2 * Math.PI / 60))); g.setColor(Color.blue); g.drawLine(xCenter, yCenter, xMinute, yMinute); // Draw hour hand int hLength = (int)(clockRadius * 0.5); int xHour = (int)(xCenter + hLength * Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); int yHour = (int)(yCenter - hLength * Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12))); g.setColor(Color.BLACK); g.drawLine(xCenter, yCenter, xHour, yHour); } public void setCurrentTime() { // Construct a calendar for the current date and time Calendar calendar = new GregorianCalendar(); // Set current hour, minute and second this.hour = calendar.get(Calendar.HOUR_OF_DAY); this.minute = calendar.get(Calendar.MINUTE); this.second = calendar.get(Calendar.SECOND); } public Dimension getPreferredSize() { return new Dimension(200, 200); }

99 99 Clock Animation Demo import java.awt.event.*; import javax.swing.*; public class ClockAnimation extends StillClock { public ClockAnimation() { // Create a timer with delay 1000 ms Timer timer = new Timer(1000, new TimerListener()); timer.start(); } private class TimerListener implements ActionListener { /** Handle the action event */ public void actionPerformed(ActionEvent e) { // Set new time and repaint the clock to display current time setCurrentTime(); repaint(); } /** Main method */ public static void main(String[] args) { JFrame frame = new JFrame("ClockAnimation"); ClockAnimation clock = new ClockAnimation(); frame.add(clock); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(200, 200); frame.setVisible(true); }

100 100 Creating User Interfaces

101 101 Components Covered in the Chapter F Introduces the frequently used GUI components F Uses borders and icons

102 102 Buttons A button is a component that triggers an action event when clicked. Swing provides regular buttons, toggle buttons, check box buttons, and radio buttons. The common features of these buttons are generalized in javax.swing.AbstractButton.

103 103 AbstractButton

104 104 JButton JButton inherits AbstractButton and provides several constructors to create buttons.

105 105 JButton Constructors The following are JButton constructors: JButton() JButton(String text) JButton(String text, Icon icon) JButton(Icon icon)

106 106 JButton Properties  text F icon F mnemonic F horizontalAlignment F verticalAlignment F horizontalTextPosition F verticalTextPosition F iconTextGap

107 107 Default Icons, Pressed Icon, and Rollover Icon A regular button has a default icon, pressed icon, and rollover icon. Normally, you use the default icon. All other icons are for special effects. A pressed icon is displayed when a button is pressed and a rollover icon is displayed when the mouse is over the button but not pressed. (A) Default icon (B) Pressed icon (C) Rollover icon

108 108 Demo import javax.swing.*; public class TestButtonIcons extends JFrame { public static void main(String[] args) { // Create a frame and set its properties JFrame frame = new TestButtonIcons(); frame.setTitle("ButtonIcons"); frame.setSize(165, 80); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public TestButtonIcons() { ImageIcon usIcon = new ImageIcon("image/usIcon.gif"); ImageIcon caIcon = new ImageIcon("image/caIcon.gif"); ImageIcon ukIcon = new ImageIcon("image/ukIcon.gif"); JButton jbt = new JButton("Click it", usIcon); jbt.setPressedIcon(caIcon); jbt.setRolloverIcon(ukIcon); add(jbt); }

109 109 Horizontal Alignments Horizontal alignment specifies how the icon and text are placed horizontally on a button. You can set the horizontal alignment using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. At present, LEADING and LEFT are the same and TRAILING and RIGHT are the same. Future implementation may distinguish them. The default horizontal alignment is SwingConstants.TRAILING.

110 110 Vertical Alignments Vertical alignment specifies how the icon and text are placed vertically on a button. You can set the vertical alignment using one of the three constants: TOP, CENTER, BOTTOM. The default vertical alignment is SwingConstants.CENTER.

111 111 Horizontal Text Positions Horizontal text position specifies the horizontal position of the text relative to the icon. You can set the horizontal text position using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. The default horizontal text position is SwingConstants.RIGHT.

112 112 Vertical Text Positions Vertical text position specifies the vertical position of the text relative to the icon. You can set the vertical text position using one of the three constants: TOP, CENTER. The default vertical text position is SwingConstants.CENTER.

113 113 Example: Using Buttons Write a program that displays a message on a panel and uses two buttons,, to move the message on the panel to the left or right. Run ButtonDemo

114 114 MessagePanel import java.awt.FontMetrics; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JPanel; public class MessagePanel extends JPanel { /** The message to be displayed */ private String message = "Welcome to Java"; /** The x coordinate where the message is displayed */ private int xCoordinate = 20; /** The y coordinate where the message is displayed */ private int yCoordinate = 20; /** Indicate whether the message is displayed in the center */ private boolean centered; /** The interval for moving the message horizontally and vertically */ private int interval = 10; /** Construct with default properties */ public MessagePanel() { } /** Construct a message panel with a specified message */ public MessagePanel(String message) { this.message = message; } /** Return message */ public String getMessage() { return message; } /** Set a new message */ public void setMessage(String message) { this.message = message; repaint(); } /** Return xCoordinator */ public int getXCoordinate() { return xCoordinate; } /** Set a new xCoordinator */ public void setXCoordinate(int x) { this.xCoordinate = x; repaint(); } /** Return yCoordinator */ public int getYCoordinate() { return yCoordinate; } /** Set a new yCoordinator */ public void setYCoordinate(int y) { this.yCoordinate = y; repaint(); }

115 115 MessagePanel /** Return centered */ public boolean isCentered() { return centered; } /** Set a new centered */ public void setCentered(boolean centered) { this.centered = centered; repaint(); } /** Return interval */ public int getInterval() { return interval; } /** Set a new interval */ public void setInterval(int interval) { this.interval = interval; repaint(); } /** Paint the message */ protected void paintComponent(Graphics g) { super.paintComponent(g); if (centered) { // Get font metrics for the current font FontMetrics fm = g.getFontMetrics(); // Find the center location to display int stringWidth = fm.stringWidth(message); int stringAscent = fm.getAscent(); // Get the position of the leftmost character in the baseline xCoordinate = getWidth() / 2 - stringWidth / 2; yCoordinate = getHeight() / 2 + stringAscent / 2; } g.drawString(message, xCoordinate, yCoordinate); } /** Move the message left */ public void moveLeft() { xCoordinate -= interval; repaint(); } /** Move the message right */ public void moveRight() { xCoordinate += interval; repaint(); } /** Move the message up */ public void moveUp() { yCoordinate -= interval; repaint(); }

116 116 MessagePanel /** Move the message down */ public void moveDown() { yCoordinate += interval; repaint(); } /** Override get method for preferredSize */ public Dimension getPreferredSize() { return new Dimension(200, 30); }

117 117 ButtonDemo import java.awt.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.*; public class ButtonDemo extends JFrame { // Create a panel for displaying message protected MessagePanel messagePanel = new MessagePanel("Welcome to Java"); // Declare two buttons to move the message left and right private JButton jbtLeft = new JButton("<="); private JButton jbtRight = new JButton("=>"); public static void main(String[] args) { ButtonDemo frame = new ButtonDemo(); frame.setTitle("ButtonDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 200); frame.setVisible(true); } public ButtonDemo() { // Set the background color of messagePanel messagePanel.setBackground(Color.white); // Create Panel jpButtons to hold two Buttons " " JPanel jpButtons = new JPanel(); jpButtons.setLayout(new FlowLayout()); jpButtons.add(jbtLeft); jpButtons.add(jbtRight); // Set keyboard mnemonics jbtLeft.setMnemonic('L'); jbtRight.setMnemonic('R'); // Set icons and remove text // jbtLeft.setIcon(new ImageIcon("image/left.gif")); // jbtRight.setIcon(new ImageIcon("image/right.gif")); // jbtLeft.setText(null); // jbtRight.setText(null); // Set tool tip text on the buttons jbtLeft.setToolTipText("Move message to left"); jbtRight.setToolTipText("Move message to right"); // Place panels in the frame setLayout(new BorderLayout()); add(messagePanel, BorderLayout.CENTER); add(jpButtons, BorderLayout.SOUTH); // Register listeners with the buttons jbtLeft.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.moveLeft(); } }); jbtRight.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.moveRight(); } }); }

118 118 ButtonDemo

119 119 JCheckBox JCheckBox inherits all the properties such as text, icon, mnemonic, verticalAlignment, horizontalAlignment, horizontalTextPosition, verticalTextPosition, and selected from AbstractButton, and provides several constructors to create check boxes.

120 120 Example: Using Check Boxes Add three check boxes named Centered, Bold, and Italic into Example ButtonDemo to let the user specify whether the message is centered, bold, or italic. ButtonDemo CheckBoxDemo

121 121 Check Box Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBoxDemo extends ButtonDemo { // Create three check boxes to control the display of message private JCheckBox jchkCentered = new JCheckBox("Centered"); private JCheckBox jchkBold = new JCheckBox("Bold"); private JCheckBox jchkItalic = new JCheckBox("Italic"); public static void main(String[] args) { CheckBoxDemo frame = new CheckBoxDemo(); frame.setTitle("CheckBoxDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500, 200); frame.setVisible(true); } public CheckBoxDemo() { // Set mnemonic keys jchkCentered.setMnemonic('C'); jchkBold.setMnemonic('B'); jchkItalic.setMnemonic('I'); // Create a new panel to hold check boxes JPanel jpCheckBoxes = new JPanel(); jpCheckBoxes.setLayout(new GridLayout(3, 1)); jpCheckBoxes.add(jchkCentered); jpCheckBoxes.add(jchkBold); jpCheckBoxes.add(jchkItalic); add(jpCheckBoxes, BorderLayout.EAST); // Register listeners with the check boxes jchkCentered.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.setCentered(jchkCentered.isSelected()); } }); jchkBold.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setNewFont(); } }); jchkItalic.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setNewFont(); } }); } private void setNewFont() { // Determine a font style int fontStyle = Font.PLAIN; fontStyle += (jchkBold.isSelected() ? Font.BOLD : Font.PLAIN); fontStyle += (jchkItalic.isSelected() ? Font.ITALIC : Font.PLAIN); // Set font for the message Font font = messagePanel.getFont(); messagePanel.setFont( new Font(font.getName(), fontStyle, font.getSize())); }

122 122 Check Box Demo

123 123 JRadioButton Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

124 124 Grouping Radio Buttons ButtonGroup btg = new ButtonGroup(); btg.add(jrb1); btg.add(jrb2);

125 125 Example: Using Radio Buttons Add three radio buttons named Red, Green, and Blue into the preceding example to let the user choose the color of the message. ButtonDemo CheckBoxDemo RadioButtonDemo

126 126 Radio Button Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButtonDemo extends CheckBoxDemo { // Declare radio buttons private JRadioButton jrbRed, jrbGreen, jrbBlue; public static void main(String[] args) { RadioButtonDemo frame = new RadioButtonDemo(); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("RadioButtonDemo"); frame.setSize(500, 200); frame.setVisible(true); } public RadioButtonDemo() { // Create a new panel to hold check boxes JPanel jpRadioButtons = new JPanel(); jpRadioButtons.setLayout(new GridLayout(3, 1)); jpRadioButtons.add(jrbRed = new JRadioButton("Red")); jpRadioButtons.add(jrbGreen = new JRadioButton("Green")); jpRadioButtons.add(jrbBlue = new JRadioButton("Blue")); add(jpRadioButtons, BorderLayout.WEST); // Create a radio button group to group three buttons ButtonGroup group = new ButtonGroup(); group.add(jrbRed); group.add(jrbGreen); group.add(jrbBlue); // Set keyboard mnemonics jrbRed.setMnemonic('E'); jrbGreen.setMnemonic('G'); jrbBlue.setMnemonic('U'); // Register listeners for check boxes jrbRed.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.setForeground(Color.red); } }); jrbGreen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.setForeground(Color.green); } }); jrbBlue.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { messagePanel.setForeground(Color.blue); } }); // Set initial message color to blue jrbBlue.setSelected(true); messagePanel.setForeground(Color.blue); }

127 127 Radio Button Demo

128 128 JLabel A label is a display area for a short text, an image, or both.

129 129 JLabel Constructors The constructors for labels are as follows: JLabel() JLabel(String text, int horizontalAlignment) JLabel(String text) JLabel(Icon icon) JLabel(Icon icon, int horizontalAlignment) JLabel(String text, Icon icon, int horizontalAlignment)

130 130 JLabel Properties JLabel inherits all the properties from JComponent and has many properties similar to the ones in JButton, such as text, icon, horizontalAlignment, verticalAlignment, horizontalTextPosition, verticalTextPosition, and iconTextGap.

131 131 Using Labels // Create an image icon from image file ImageIcon icon = new ImageIcon("image/grapes.gif"); // Create a label with text, an icon, // with centered horizontal alignment JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER); // Set label's text alignment and gap between text and icon jlbl.setHorizontalTextPosition(SwingConstants.CENTER); jlbl.setVerticalTextPosition(SwingConstants.BOTTOM); jlbl.setIconTextGap(5);

132 132 JTextField A text field is an input area where the user can type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).

133 133 JTextField Constructors F JTextField(int columns) Creates an empty text field with the specified number of columns. F JTextField(String text) Creates a text field initialized with the specified text.  JTextField(String text, int columns) Creates a text field initialized with the specified text and the column size.

134 134 JTextField Properties  text F horizontalAlignment F editable F columns

135 135 JTextField Methods F getText() Returns the string from the text field. F setText(String text) Puts the given string in the text field. F setEditable(boolean editable) Enables or disables the text field to be edited. By default, editable is true. F setColumns(int) Sets the number of columns in this text field. The length of the text field is changeable.

136 136 Example: Using Text Fields Add a text field to the preceding example to let the user set a new message.

137 137 Text Field Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextFieldDemo extends RadioButtonDemo { private JTextField jtfMessage = new JTextField(10); /** Main method */ public static void main(String[] args) { TextFieldDemo frame = new TextFieldDemo(); frame.pack(); frame.setTitle("TextFieldDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public TextFieldDemo() { // Create a new panel to hold label and text field JPanel jpTextField = new JPanel(); jpTextField.setLayout(new BorderLayout(5, 0)); jpTextField.add( new JLabel("Enter a new message"), BorderLayout.WEST); jpTextField.add(jtfMessage, BorderLayout.CENTER); add(jpTextField, BorderLayout.NORTH); jtfMessage.setHorizontalAlignment(JTextField.RIGHT); // Register listener jtfMessage.addActionListener(new ActionListener() { /** Handle ActionEvent */ public void actionPerformed(ActionEvent e) { messagePanel.setMessage(jtfMessage.getText()); jtfMessage.requestFocusInWindow(); } }); }

138 138 JTextArea If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.

139 139 JTextArea Constructors  JTextArea(int rows, int columns) Creates a text area with the specified number of rows and columns.  JTextArea(String s, int rows, int columns) Creates a text area with the initial text and the number of rows and columns specified.

140 140 JTextArea Properties  text F editable F columns F lineWrap F wrapStyleWord F rows F lineCount F tabSize

141 141 Example: Using Text Areas  This example gives a program that displays an image in a label, a title in a label, and a text in a text area.

142 142 Using Text Area Demo import java.awt.*; import javax.swing.*; public class TextAreaDemo extends JFrame { // Declare and create a description panel private DescriptionPanel descriptionPanel = new DescriptionPanel(); public static void main(String[] args) { TextAreaDemo frame = new TextAreaDemo(); frame.pack(); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("TextAreaDemo"); frame.setVisible(true); } public TextAreaDemo() { // Set title, text and image in the description panel descriptionPanel.setTitle("Canada"); String description = "The Maple Leaf flag \n\n" + "The Canadian National Flag was adopted by the Canadian " + "Parliament on October 22, 1964 and was proclaimed into law " + "by Her Majesty Queen Elizabeth II (the Queen of Canada) on " + "February 15, 1965. The Canadian Flag (colloquially known " + "as The Maple Leaf Flag) is a red flag of the proportions " + "two by length and one by width, containing in its center a " + "white square, with a single red stylized eleven-point " + "mapleleaf centered in the white square."; descriptionPanel.setDescription(description); descriptionPanel.setImageIcon(new ImageIcon("image/ca.gif")); // Add the description panel to the frame setLayout(new BorderLayout()); add(descriptionPanel, BorderLayout.CENTER); } // Define a panel for displaying image and text class DescriptionPanel extends JPanel { /** Label for displaying an image icon and a text */ private JLabel jlblImageTitle = new JLabel(); /** Text area for displaying text */ private JTextArea jtaDescription = new JTextArea(); public DescriptionPanel() { // Center the icon and text and place the text under the icon jlblImageTitle.setHorizontalAlignment(JLabel.CENTER); jlblImageTitle.setHorizontalTextPosition(JLabel.CENTER); jlblImageTitle.setVerticalTextPosition(JLabel.BOTTOM); // Set the font in the label and the text field jlblImageTitle.setFont(new Font("SansSerif", Font.BOLD, 16)); jtaDescription.setFont(new Font("Serif", Font.PLAIN, 14)); // Set lineWrap and wrapStyleWord true for the text area jtaDescription.setLineWrap(true); jtaDescription.setWrapStyleWord(true); jtaDescription.setEditable(false);

143 143 Using Text Area Demo // Create a scroll pane to hold the text area JScrollPane scrollPane = new JScrollPane(jtaDescription); // Set BorderLayout for the panel, add label and scrollpane setLayout(new BorderLayout(5, 5)); add(scrollPane, BorderLayout.CENTER); add(jlblImageTitle, BorderLayout.WEST); } /** Set the title */ public void setTitle(String title) { jlblImageTitle.setText(title); } /** Set the image icon */ public void setImageIcon(ImageIcon icon) { jlblImageTitle.setIcon(icon); } /** Set the text description */ public void setDescription(String text) { jtaDescription.setText(text); }

144 144 JComboBox A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value.

145 145 JComboBox Methods To add an item to a JComboBox jcbo, use jcbo.addItem(Object item) To get an item from JComboBox jcbo, use jcbo.getItem()

146 146 Using the itemStateChanged Handler public void itemStateChanged(ItemEvent e) { // Make sure the source is a combo box if (e.getSource() instanceof JComboBox) String s = (String)e.getItem(); } When a choice is checked or unchecked, itemStateChanged() for ItemEvent is invoked as well as the actionPerformed() handler for ActionEvent.

147 147 Example: Using Combo Boxes This example lets users view an image and a description of a country's flag by selecting the country from a combo box.

148 148 Using Combo Box Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBoxDemo extends JFrame { // Declare an array of Strings for flag titles private String[] flagTitles = {"Canada", "China", "Denmark", "France", "Germany", "India", "Norway", "United Kingdom", "United States of America"}; // Declare an ImageIcon array for the national flags of 9 countries private ImageIcon[] flagImage = { new ImageIcon("image/ca.gif"), new ImageIcon("image/china.gif"), new ImageIcon("image/denmark.gif"), new ImageIcon("image/fr.gif"), new ImageIcon("image/germany.gif"), new ImageIcon("image/india.gif"), new ImageIcon("image/norway.gif"), new ImageIcon("image/uk.gif"), new ImageIcon("image/us.gif") }; // Declare an array of strings for flag descriptions private String[] flagDescription = new String[9]; // Declare and create a description panel private DescriptionPanel descriptionPanel = new DescriptionPanel(); // Create a combo box for selecting countries private JComboBox jcbo = new JComboBox(flagTitles); public ComboBoxDemo() { // Set text description flagDescription[0] = "The Maple Leaf flag \n\n" + "The Canadian National Flag was adopted by the Canadian " + "Parliament on October 22, 1964 and was proclaimed into law " + "by Her Majesty Queen Elizabeth II (the Queen of Canada) on " + "February 15, 1965. The Canadian Flag (colloquially known " + "as The Maple Leaf Flag) is a red flag of the proportions " + "two by length and one by width, containing in its center a " + "white square, with a single red stylized eleven-point " + "mapleleaf centered in the white square."; flagDescription[1] = "Description for China... "; flagDescription[2] = "Description for Denmark... "; flagDescription[3] = "Description for France... "; flagDescription[4] = "Description for Germany... "; flagDescription[5] = "Description for India... "; flagDescription[6] = "Description for Norway... "; flagDescription[7] = "Description for UK... "; flagDescription[8] = "Description for US... "; // Set the first country (Canada) for display setDisplay(0); // Add combo box and description panel to the list add(jcbo, BorderLayout.NORTH); add(descriptionPanel, BorderLayout.CENTER); // Register listener jcbo.addItemListener(new ItemListener() { /** Handle item selection */ public void itemStateChanged(ItemEvent e) { setDisplay(jcbo.getSelectedIndex()); } }); }

149 149 Using Combo Box Demo /** Set display information on the description panel */ public void setDisplay(int index) { descriptionPanel.setTitle(flagTitles[index]); descriptionPanel.setImageIcon(flagImage[index]); descriptionPanel.setDescription(flagDescription[index]); } public static void main(String[] args) { ComboBoxDemo frame = new ComboBoxDemo(); frame.pack(); frame.setTitle("ComboBoxDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

150 150 JList A list is a component that performs basically the same function as a combo box, but it enables the user to choose a single value or multiple values.

151 151 JList Constructors  JList() Creates an empty list. F JList(Object[] stringItems) Creates a new list initialized with items.

152 152 JList Properties  selectedIndexd F selectedIndices F selectedValue F selectedValues F selectionMode F visibleRowCount

153 153 Example: Using Lists This example gives a program that lets users select countries in a list and display the flags of the selected countries in the labels. RunListDemo

154 154 Using Lists import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class ListDemo extends JFrame { final int NUMBER_OF_FLAGS = 9; // Declare an array of Strings for flag titles private String[] flagTitles = {"Canada", "China", "Denmark", "France", "Germany", "India", "Norway", "United Kingdom", "United States of America"}; // The list for selecting countries private JList jlst = new JList(flagTitles); // Declare an ImageIcon array for the national flags of 9 countries private ImageIcon[] imageIcons = { new ImageIcon("image/ca.gif"), new ImageIcon("image/china.gif"), new ImageIcon("image/denmark.gif"), new ImageIcon("image/fr.gif"), new ImageIcon("image/germany.gif"), new ImageIcon("image/india.gif"), new ImageIcon("image/norway.gif"), new ImageIcon("image/uk.gif"), new ImageIcon("image/us.gif") }; // Arrays of labels for displaying images private JLabel[] jlblImageViewer = new JLabel[NUMBER_OF_FLAGS]; public static void main(String[] args) { ListDemo frame = new ListDemo(); frame.setSize(650, 500); frame.setTitle("ListDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public ListDemo() { // Create a panel to hold nine labels JPanel p = new JPanel(new GridLayout(3, 3, 5, 5)); for (int i = 0; i < NUMBER_OF_FLAGS; i++) { p.add(jlblImageViewer[i] = new JLabel()); jlblImageViewer[i].setHorizontalAlignment (SwingConstants.CENTER); } // Add p and the list to the frame add(p, BorderLayout.CENTER); add(new JScrollPane(jlst), BorderLayout.WEST); // Register listeners jlst.addListSelectionListener(new ListSelectionListener() { /** Handle list selection */ public void valueChanged(ListSelectionEvent e) { // Get selected indices int[] indices = jlst.getSelectedIndices(); int i; // Set icons in the labels for (i = 0; i < indices.length; i++) { jlblImageViewer[i].setIcon(imageIcons[indices[i]]); }

155 155 Using Lists // Remove icons from the rest of the labels for (; i < NUMBER_OF_FLAGS; i++) { jlblImageViewer[i].setIcon(null); } }); }

156 156 JScrollBar A scroll bar is a control that enables the user to select from a range of values. The scrollbar appears in two styles: horizontal and vertical.

157 157 Scroll Bar Properties

158 158 Example: Using Scrollbars This example uses horizontal and vertical scrollbars to control a message displayed on a panel. The horizontal scrollbar is used to move the message to the left or the right, and the vertical scrollbar to move it up and down.

159 159 Scroll Bar Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ScrollBarDemo extends JFrame { // Create horizontal and vertical scroll bars private JScrollBar jscbHort = new JScrollBar(JScrollBar.HORIZONTAL); private JScrollBar jscbVert = new JScrollBar(JScrollBar.VERTICAL); // Create a MessagePanel private MessagePanel messagePanel = new MessagePanel("Welcome to Java"); public static void main(String[] args) { ScrollBarDemo frame = new ScrollBarDemo(); frame.setTitle("ScrollBarDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public ScrollBarDemo() { // Add scroll bars and message panel to the frame setLayout(new BorderLayout()); add(messagePanel, BorderLayout.CENTER); add(jscbVert, BorderLayout.EAST); add(jscbHort, BorderLayout.SOUTH); // Register listener for the scroll bars jscbHort.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { // getValue() and getMaximumValue() return int, but for better // precision, use double double value = jscbHort.getValue(); double maximumValue = jscbHort.getMaximum(); double newX = (value * messagePanel.getWidth() / maximumValue); messagePanel.setXCoordinate((int) newX); } }); jscbVert.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { // getValue() and getMaximumValue() return int, but for better // precision, use double double value = jscbVert.getValue(); double maximumValue = jscbVert.getMaximum(); double newY = (value * messagePanel.getHeight() / maximumValue); messagePanel.setYCoordinate((int)newY); } }); }

160 160 Scroll Bar Demo

161 161 JSlider JSlider is similar to JScrollBar, but JSlider has more properties and can appear in many forms.

162 162 Example: Using Sliders Rewrite the preceding program using the sliders to control a message displayed on a panel instead of using scroll bars.

163 163 Sliders Demo import java.awt.*; import javax.swing.*; import javax.swing.event.*; public class SliderDemo extends JFrame { // Create horizontal and vertical sliders private JSlider jsldHort = new JSlider(JSlider.HORIZONTAL); private JSlider jsldVert = new JSlider(JSlider.VERTICAL); // Create a MessagePanel private MessagePanel messagePanel = new MessagePanel("Welcome to Java"); public static void main(String[] args) { SliderDemo frame = new SliderDemo(); frame.setTitle("SliderDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public SliderDemo() { // Add sliders and message panel to the frame setLayout(new BorderLayout(5, 5)); add(messagePanel, BorderLayout.CENTER); add(jsldVert, BorderLayout.EAST); add(jsldHort, BorderLayout.SOUTH); // Set properties for sliders jsldHort.setMaximum(50); jsldHort.setPaintLabels(true); jsldHort.setPaintTicks(true); jsldHort.setMajorTickSpacing(10); jsldHort.setMinorTickSpacing(1); jsldHort.setPaintTrack(false); jsldVert.setInverted(true); jsldVert.setMaximum(10); jsldVert.setPaintLabels(true); jsldVert.setPaintTicks(true); jsldVert.setMajorTickSpacing(10); jsldVert.setMinorTickSpacing(1); // Register listener for the sliders jsldHort.addChangeListener(new ChangeListener() { /** Handle scroll bar adjustment actions */ public void stateChanged(ChangeEvent e) { // getValue() and getMaximumValue() return int, but for better // precision, use double double value = jsldHort.getValue(); double maximumValue = jsldHort.getMaximum(); double newX = (value * messagePanel.getWidth() / maximumValue); messagePanel.setXCoordinate((int)newX); } });

164 164 Sliders Demo jsldVert.addChangeListener(new ChangeListener() { /** Handle scroll bar adjustment actions */ public void stateChanged(ChangeEvent e) { // getValue() and getMaximumValue() return int, but for better // precision, use double double value = jsldVert.getValue(); double maximumValue = jsldVert.getMaximum(); double newY = (value * messagePanel.getHeight() / maximumValue); messagePanel.setYCoordinate((int) newY); } }); }

165 165 Creating Multiple Windows The following slides show step-by-step how to create an additional window from an application or applet.

166 166 Step 1: Create a subclass of JFrame (called a SubFrame ) that tells the new window what to do. For example, all the GUI application programs extend JFrame and are subclasses of JFrame. Creating Additional Windows, Step 1

167 167 Creating Additional Windows, Step 2 Step 2: Create an instance of SubFrame in the application or applet. Example: SubFrame subFrame = new SubFrame("SubFrame Title");

168 168 Creating Additional Windows, Step 3 Step 3: Create a JButton for activating the subFrame. add(new JButton("Activate SubFrame"));

169 169 Creating Additional Windows, Step 4 Step 4: Override the actionPerformed() method as follows: public actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (e.target instanceof Button) { if ("Activate SubFrame".equals(actionCommand)) { subFrame.setVisible(true); }

170 170 Example: Creating Multiple Windows F This example creates a main window with a text area in the scroll pane, and a button named "Show Histogram." When the user clicks the button, a new window appears that displays a histogram to show the occurrence of the letters in the text area.

171 171 Histogram import javax.swing.*; import java.awt.*; public class Histogram extends JPanel { // Count the occurrence of 26 letters private int[] count; /** Set the count and display histogram */ public void showHistogram(int[] count) { this.count = count; repaint(); } /** Paint the histogram */ protected void paintComponent(Graphics g) { if (count == null) return; // No display if count is null super.paintComponent(g); // Find the panel size and bar width and interval dynamically int width = getWidth(); int height = getHeight(); int interval = (width - 40) / count.length; int individualWidth = (int)(((width - 40) / 24) * 0.60); // Find the maximum count. The maximum count has the highest bar int maxCount = 0; for (int i = 0; i < count.length; i++) { if (maxCount < count[i]) maxCount = count[i]; } // x is the start position for the first bar in the histogram int x = 30; // Draw a horizontal base line g.drawLine(10, height - 45, width - 10, height - 45); for (int i = 0; i < count.length; i++) { // Find the bar height int barHeight = (int)(((double)count[i] / (double)maxCount) * (height - 55)); // Display a bar (i.e. rectangle) g.drawRect(x, height - 45 - barHeight, individualWidth, barHeight); // Display a letter under the base line g.drawString((char)(65 + i) + "", x, height - 30); // Move x for displaying the next character x += interval; } /** Override getPreferredSize */ public Dimension getPreferredSize() { return new Dimension(300, 300); }

172 172 Multiple Windows Demo import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MultipleWindowsDemo extends JFrame { private JTextArea jta; private JButton jbtShowHistogram = new JButton("Show Histogram"); private Histogram histogram = new Histogram(); // Create a new frame to hold the histogram panel private JFrame histogramFrame = new JFrame(); public MultipleWindowsDemo() { // Store text area in a scroll pane JScrollPane scrollPane = new JScrollPane(jta = new JTextArea()); scrollPane.setPreferredSize(new Dimension(300, 200)); jta.setWrapStyleWord(true); jta.setLineWrap(true); // Place scroll pane and button in the frame add(scrollPane, BorderLayout.CENTER); add(jbtShowHistogram, BorderLayout.SOUTH); // Register listener jbtShowHistogram.addActionListener(new ActionListener() { /** Handle the button action */ public void actionPerformed(ActionEvent e) { // Count the letters in the text area int[] count = countLetters(); // Set the letter count to histogram for display histogram.showHistogram(count); histogramFrame.setVisible(true); // Show the frame } }); // Create a new frame to hold the histogram panel histogramFrame.add(histogram); histogramFrame.pack(); histogramFrame.setTitle("Histogram"); } /** Count the letters in the text area */ private int[] countLetters() { // Count for 26 letters int[] count = new int[26]; // Get contents from the text area String text = jta.getText(); // Count occurrence of each letter (case insensitive) for (int i = 0; i < text.length(); i++) { char character = text.charAt(i); if ((character >= 'A') && (character <= 'Z')) { count[(int)character - 65]++; // The ASCII for 'A' is 65 } else if ((character >= 'a') && (character <= 'z')) { count[(int)character - 97]++; // The ASCII for 'a' is 97 } return count; // Return the count array }

173 173 Multiple Windows Demo public static void main(String[] args) { MultipleWindowsDemo frame = new MultipleWindowsDemo(); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("MultipleWindowsDemo"); frame.pack(); frame.setVisible(true); }


Download ppt "1 Chapter 6 GUI Basics. 2 Objectives F To distinguish simple GUI components. F To describe the Java GUI API hierarchy. F To create user interfaces using."

Similar presentations


Ads by Google