Chapter 17 – Graphical User Interfaces Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Slides:



Advertisements
Similar presentations
Chapter 19 – Graphical User Interfaces
Advertisements

Graphical User Interfaces (Part IV)
Graphical User Interfaces, 2D Graphics & Game Programming.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Ten: Inheritance.
Chapter Eighteen: Graphical User Interfaces. Chapter Goals To understand the use of layout managers to arrange user- interface components in a container.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Inheritance Review CSC 171 FALL 2004 LECTURE 19. READING Read Horstmann, Chapter 11 Look at Chapter 12 – Will not be on MT or Final – One lab Begin Reading.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
Chapter 19 – Graphical User Interfaces. Chapter Goals  To use layout managers to arrange user ‑ interface components in a container  To become familiar.
Java Programming Chapter 10 Graphical User Interfaces.
GUIs Mimi Opkins CECS277.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Combo Box, Check Boxes, and Radio Buttons. Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive.
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
객체지향프로그래밍강원대학교 1/90 9 주 그래픽사용자인터페이스 9 주 강의 목표 상속을 이용한 프레임 구성법 이해 컨테이너를 이용하는 컴포넌트 배치 방법 이해 배치관리자 사용법 연습 Swing 컴포넌트 사용법 및 문서 찾는 요령 습득.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
1 Why layout managers Can we perform layout without them? –Yes. A container’s layout property can be set to null. Absolute positioning: specify size and.
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Chapters (ArrayList / Generic)
Chapter 14 Graphical User Interfaces. Chapter Goals To use inheritance to customize frames To understand how user-interface components are added to a.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
Copyright © 2013 by John Wiley & Sons. All rights reserved. GRAPHICAL USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/11.
Graphical User Interface. Chapter Goals To understand the use of layout managers to arrange user- interface components in a container To become familiar.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine and Ten Graphics.
Fall 2006Adapted from Java Concepts Companion Slides1 Graphical User Interfaces Advanced Programming ICOM 4015 Lecture 12 Reading: Java Concepts Chapter.
Chapter 14 Graphical User Interfaces. Chapter Goals To use inheritance to customize frames To understand how user-interface components are added to a.
Java Programming Week 4: Inheritance (Chapter 10).
Chapter 12: Graphical User Interfaces 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 12 Graphical User Interfaces JAVA.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
CSE 501N Fall ‘09 18: Java GUI (Swing) 10 November 2009 Nick Leidenfrost.
Copyright © 2013 by John Wiley & Sons. All rights reserved. ADVANCED USER INTERFACES CHAPTER Slides by Donald W. Smith TechNeTrain.com Final Draft 10/30/2011.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CHAPTER 10 EVENT HANDLING. CHAPTER GOALS To understand the Java event model To install mouse and action listeners To accept mouse and text input To display.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 12: Graphical User Interfaces 1 Chapter 12 Graphical User Interfaces.
GUI Components CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
GUI Tutorial 1. A Bit of Philosophy on what to Teach  There are numerous libraries, frameworks, options  Modern GUIs are often developed using XML (e.g.,
Chapter 14 Graphical User Interfaces. Chapter Goals To understand how to create frames To use inheritance to customize frames To understand how user-interface.
Java Programming Week 5: Graphical User Interfaces (Chapter 18)
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Event Handling and GUI Components.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Event Handler Methods Text field Object Responder JAVA AWT Environment: Messages are sent between JAVA Objects Screen Event Notification Press Button.
CHAPTER 12 GRAPHICAL USER INTERFACES. CHAPTER GOALS To use inheritance to customize panels and frames To understand how user interface components are.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
Chapter Ten: Inheritance
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Lecture 16 More GUI programming
Chapter 13: Advanced GUIs and Graphics
Chapter 20 – Graphical User Interfaces
Timer class and inner classes
Chapter 14 Graphical User Interfaces
Chapter 12 Event Handling
Graphical User Interface
Presentation transcript:

Chapter 17 – Graphical User Interfaces Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Goals G To become familiar with common user-interface components, such as buttons, combo boxes, text areas, and menus G To understand the use of layout managers to arrange user- interface components in a container G To build programs that handle events from user-interface components To learn how to browse the Java documentation

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Processing Text Input Use JTextField components to provide space for user input: final int FIELD_WIDTH = 10; // In characters final JTextField rateField = new JTextField(FIELD_WIDTH); Place a JLabel next to each text field: JLabel rateLabel = new JLabel("Interest Rate: ");

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Processing Text Input Supply a button that the user can press to indicate that the input is ready for processing:

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Processing Text Input The actionPerformed method of the button's ActionListener reads the user input from the text fields (use getText ): class AddInterestListener implements ActionListener { public void actionPerformed(ActionEvent event) { double rate = Double.parseDouble(rateField.getText()); double interest = account.getBalance() * rate / 100; account.deposit(interest); resultLabel.setText("balance: ” + account.getBalance()); }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textfield/InvestmentViewer3.java 1 import javax.swing.JFrame; 2 3 /** 4 This program displays the growth of an investment. 5 */ 6 public class InvestmentViewer3 7 { 8 public static void main(String[] args) 9 { 10 JFrame frame = new InvestmentFrame(); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 frame.setVisible(true); 13 } 14 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textfield/InvestmentFrame.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 import javax.swing.JButton; 4 import javax.swing.JFrame; 5 import javax.swing.JLabel; 6 import javax.swing.JPanel; 7 import javax.swing.JTextField; 8 9 /** 10 A frame that shows the growth of an investment with variable interest. 11 */ 12 public class InvestmentFrame extends JFrame 13 { 14 private static final int FRAME_WIDTH = 450; 15 private static final int FRAME_HEIGHT = 100; private static final double DEFAULT_RATE = 5; 18 private static final double INITIAL_BALANCE = 1000; 19 Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textfield/InvestmentFrame.java (cont.) 20 private JLabel rateLabel; 21 private JTextField rateField; 22 private JButton button; 23 private JLabel resultLabel; 24 private JPanel panel; 25 private BankAccount account; public InvestmentFrame() 28 { 29 account = new BankAccount(INITIAL_BALANCE); // Use instance variables for components 32 resultLabel = new JLabel("balance: " + account.getBalance()); // Use helper methods 35 createTextField(); 36 createButton(); 37 createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); 40 } Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textfield/InvestmentFrame.java (cont.) 42 private void createTextField() 43 { 44 rateLabel = new JLabel("Interest Rate: "); final int FIELD_WIDTH = 10; 47 rateField = new JTextField(FIELD_WIDTH); 48 rateField.setText("" + DEFAULT_RATE); 49 } 50 Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textfield/InvestmentFrame.java (cont.) 51 private void createButton() 52 { 53 button = new JButton("Add Interest"); class AddInterestListener implements ActionListener 56 { 57 public void actionPerformed(ActionEvent event) 58 { 59 double rate = Double.parseDouble(rateField.getText()); 60 double interest = account.getBalance() * rate / 100; 61 account.deposit(interest); 62 resultLabel.setText("balance: " + account.getBalance()); 63 } 64 } 65 Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textfield/InvestmentFrame.java (cont.) 70 private void createPanel() 71 { 72 panel = new JPanel(); 73 panel.add(rateLabel); 74 panel.add(rateField); 75 panel.add(button); 76 panel.add(resultLabel); 77 add(panel); 78 } 79 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.1 What happens if you omit the first JLabel object? Answer: Then the text field is not labeled, and the user will not know its purpose.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.2 If a text field holds an integer, what expression do you use to read its contents? Answer: Integer.parseInt(textField.getText())

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Text Areas Use a JTextArea to show multiple lines of text You can specify the number of rows and columns: final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS); setText : to set the text of a text field or text area append : to add text to the end of a text area Use newline characters to separate lines: textArea.append(account.getBalance() + "\n"); To use for display purposes only: textArea.setEditable(false); // program can call setText and append to change it

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Text Areas Classes JTextField and JTextArea are subclasses of library class JTextComponent Methods setText and setEditable are declared in the JTextComponent class and inherited by JTextField and JTextArea Method append is declared in the JTextArea class

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Text Areas To add scroll bars to a text area: JTextArea textArea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea);

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textarea/InvestmentFrame.java 1 import java.awt.event.ActionEvent; 2 import java.awt.event.ActionListener; 3 import javax.swing.JButton; 4 import javax.swing.JFrame; 5 import javax.swing.JLabel; 6 import javax.swing.JPanel; 7 import javax.swing.JScrollPane; 8 import javax.swing.JTextArea; 9 import javax.swing.JTextField; /** 12 A frame that shows the growth of an investment with variable interest. 13 */ 14 public class InvestmentFrame extends JFrame 15 { 16 private static final int FRAME_WIDTH = 400; 17 private static final int FRAME_HEIGHT = 250; private static final int AREA_ROWS = 10; 20 private static final int AREA_COLUMNS = 30; 21 private static final double DEFAULT_RATE = 5; 22 private static final double INITIAL_BALANCE = 1000; Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textarea/InvestmentFrame.java (cont.) private JLabel rateLabel; 25 private JTextField rateField; 26 private JButton button; 27 private JTextArea resultArea; 28 private JPanel panel; 29 private BankAccount account; public InvestmentFrame() 32 { 33 account = new BankAccount(INITIAL_BALANCE); 34 resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS); 35 resultArea.setEditable(false); // Use helper methods 38 createTextField(); 39 createButton(); 40 createPanel(); setSize(FRAME_WIDTH, FRAME_HEIGHT); 43 } 44 Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textarea/InvestmentFrame.java (cont.) 45 private void createTextField() 46 { 47 rateLabel = new JLabel("Interest Rate: "); final int FIELD_WIDTH = 10; 50 rateField = new JTextField(FIELD_WIDTH); 51 rateField.setText("" + DEFAULT_RATE); 52 } private void createButton() 55 { 56 button = new JButton("Add Interest"); class AddInterestListener implements ActionListener 59 { 60 public void actionPerformed(ActionEvent event) 61 { 62 double rate = Double.parseDouble(rateField.getText()); 63 double interest = account.getBalance() * rate / 100; 64 account.deposit(interest); 65 resultArea.append(account.getBalance() + "\n"); 66 } 67 } 68 Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/textarea/InvestmentFrame.java (cont.) 69 ActionListener listener = new AddInterestListener(); 70 button.addActionListener(listener); 71 } private void createPanel() 74 { 75 panel = new JPanel(); 76 panel.add(rateLabel); 77 panel.add(rateField); 78 panel.add(button); 79 JScrollPane scrollPane = new JScrollPane(resultArea); 80 panel.add(scrollPane); 81 add(panel); 82 } 83 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.3 What is the difference between a text field and a text area? Answer: A text field holds a single line of text; a text area holds multiple lines.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.4 Why did the InvestmentFrame program call resultArea.setEditable(false) ? Answer: The text area is intended to display the program output. It does not collect user input.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.5 How would you modify the InvestmentFrame program if you didn’t want to use scroll bars? Answer: Don’t construct a JScrollPane and add the resultArea object directly to the frame.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Layout Management Up to now, we have had limited control over layout of components When we used a panel, it arranged the components from the left to the right User-interface components are arranged by placing them inside containers Containers can be placed inside larger containers Each container has a layout manager that directs the arrangement of its components Three useful layout managers: border layout flow layout grid layout

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Layout Management By default, JPanel places components from left to right and starts a new row when needed Panel layout carried out by FlowLayout layout manager Can set other layout managers: panel.setLayout(new BorderLayout());

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Border Layout Border layout groups container into five areas - center, north, west, south and east

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Border Layout Default layout manager for a frame (technically, the frame’s content pane) When adding a component, specify the position like this: panel.add(component, BorderLayout.NORTH); Expands each component to fill the entire allotted area If that is not desirable, place each component inside a panel

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Grid Layout Arranges components in a grid with a fixed number of rows and columns Resizes each component so that they all have same size Expands each component to fill the entire allotted area Add the components, row by row, left to right: JPanel numberPanel = new JPanel(); numberPanel.setLayout(new GridLayout(4, 3)); numberPanel.add(button7); numberPanel.add(button8); numberPanel.add(button9); numberPanel.add(button4);...

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Grid Layout

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Grid Bag Layout Tabular arrangement of components Columns can have different sizes Components can span multiple columns Quite complex to use Not covered in the book Fortunately, you can create acceptable-looking layouts by nesting panels Give each panel an appropriate layout manager Panels don’t have visible borders Use as many panels as needed to organize components

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Nesting Panels Example Keypad from the ATM GUI in Chapter 12: JPanel keypadPanel = new JPanel(); keypadPanel.setLayout(new BorderLayout()); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 3)); buttonPanel.add(button7); buttonPanel.add(button8); //... keypadPanel.add(buttonPanel, BorderLayout.CENTER); JTextField display = new JTextField(); keypadPanel.add(display, BorderLayout.NORTH);

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Nesting Panels Example

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.6 How do you add two buttons to the north area of a frame? Answer: First add them to a panel, then add the panel to the north end of a frame.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.7 How can you stack three buttons on top of each other? Answer: Place them inside a panel with a GridLayout that has three rows and one column.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Choices Radio buttons Check boxes Combo boxes

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Radio Buttons For a small set of mutually exclusive choices, use radio buttons or a combo box In a radio button set, only one button can be selected at a time When a button is selected, previously selected button in set is automatically turned off

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Radio Buttons In previous figure, font sizes are mutually exclusive: JRadioButton smallButton = new JRadioButton("Small"); JRadioButton mediumButton = new JRadioButton("Medium"); JRadioButton largeButton = new JRadioButton("Large"); // Add radio buttons into a ButtonGroup so that // only one button in group is on at any time ButtonGroup group = new ButtonGroup(); group.add(smallButton); group.add(mediumButton); group.add(largeButton);

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Radio Buttons Button group does not place buttons close to each other on container It is your job to arrange buttons on screen isSelected : Called to find out if a button is currently selected or not: if(largeButton.isSelected()) size = LARGE_SIZE Call setSelected(true) on a radio button in group before making the enclosing frame visible

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Borders Place a border around a panel to group its contents visually EtchedBorder : Three-dimensional etched effect Can add a border to any component, but most commonly to panels: JPanel panel = new JPanel(); panel.setBorder(new EtchedBorder()); TitledBorder : A border with a title: panel.setBorder(new TitledBorder(new EtchedBorder(), "Size"));

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Check Boxes Two states: Checked and unchecked Use one checkbox for a binary choice Use a group of check boxes when one selection does not exclude another Example: “Bold” and “Italic” in previous figure Construct by giving the name in the constructor: JCheckBox italicCheckBox = new JCheckBox("Italic"); Don’t place into a button group

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Combo Boxes For a large set of choices, use a combo box Uses less space than radio buttons “Combo”: Combination of a list and a text field The text field displays the name of the current selection

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Combo Boxes If combo box is editable, user can type own selection Use setEditable method Add strings with addItem method: JComboBox facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif");... Get user selection with getSelectedItem (return type is Object ): String selectedString = (String) facenameCombo.getSelectedItem(); Select an item with setSelectedItem

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Radio Buttons, Check Boxes, and Combo Boxes They generate an ActionEvent whenever the user selects an item An example: FontViewerFrame

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Radio Buttons, Check Boxes, and Combo Boxes All components notify the same listener object When user clicks on any component, we ask each component for its current content Then redraw text sample with the new font

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Classes of the Font Viewer Program

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewer.java 1 import javax.swing.JFrame; 2 3 /** 4 This program allows the user to view font effects. 5 */ 6 public class FontViewer 7 { 8 public static void main(String[] args) 9 { 10 JFrame frame = new FontViewerFrame(); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 frame.setTitle("FontViewer"); 13 frame.setVisible(true); 14 } 15 }

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java 1 import java.awt.BorderLayout; 2 import java.awt.Font; 3 import java.awt.GridLayout; 4 import java.awt.event.ActionEvent; 5 import java.awt.event.ActionListener; 6 import javax.swing.ButtonGroup; 7 import javax.swing.JButton; 8 import javax.swing.JCheckBox; 9 import javax.swing.JComboBox; 10 import javax.swing.JFrame; 11 import javax.swing.JLabel; 12 import javax.swing.JPanel; 13 import javax.swing.JRadioButton; 14 import javax.swing.border.EtchedBorder; 15 import javax.swing.border.TitledBorder; 16

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 17 /** 18 This frame contains a text field and a control panel 19 to change the font of the text. 20 */ 21 public class FontViewerFrame extends JFrame 22 { 23 private static final int FRAME_WIDTH = 300; 24 private static final int FRAME_HEIGHT = 400; private JLabel sampleField; 27 private JCheckBox italicCheckBox; 28 private JCheckBox boldCheckBox; 29 private JRadioButton smallButton; 30 private JRadioButton mediumButton; 31 private JRadioButton largeButton; 32 private JComboBox facenameCombo; 33 private ActionListener listener; 34

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 35 /** 36 Constructs the frame. 37 */ 38 public FontViewerFrame() 39 { 40 // Construct text sample 41 sampleField = new JLabel("Big Java"); 42 add(sampleField, BorderLayout.CENTER); // This listener is shared among all components 45 class ChoiceListener implements ActionListener 46 { 47 public void actionPerformed(ActionEvent event) 48 { 49 setSampleFont(); 50 } 51 } listener = new ChoiceListener(); createControlPanel(); 56 setSampleFont(); 57 setSize(FRAME_WIDTH, FRAME_HEIGHT); 58 } 59

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 60 /** 61 Creates the control panel to change the font. 62 */ 63 public void createControlPanel() 64 { 65 JPanel facenamePanel = createComboBox(); 66 JPanel sizeGroupPanel = createCheckBoxes(); 67 JPanel styleGroupPanel = createRadioButtons(); // Line up component panels JPanel controlPanel = new JPanel(); 72 controlPanel.setLayout(new GridLayout(3, 1)); 73 controlPanel.add(facenamePanel); 74 controlPanel.add(sizeGroupPanel); 75 controlPanel.add(styleGroupPanel); // Add panels to content pane add(controlPanel, BorderLayout.SOUTH); 80 } 81

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 82 /** 83 Creates the combo box with the font style choices. the panel containing the combo box 85 */ 86 public JPanel createComboBox() 87 { 88 facenameCombo = new JComboBox(); 89 facenameCombo.addItem("Serif"); 90 facenameCombo.addItem("SansSerif"); 91 facenameCombo.addItem("Monospaced"); 92 facenameCombo.setEditable(true); 93 facenameCombo.addActionListener(listener); JPanel panel = new JPanel(); 96 panel.add(facenameCombo); 97 return panel; 98 } 99

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 100 /** 101 Creates the check boxes for selecting bold and italic styles. the panel containing the check boxes 103 */ 104 public JPanel createCheckBoxes() 105 { 106 italicCheckBox = new JCheckBox("Italic"); 107 italicCheckBox.addActionListener(listener); boldCheckBox = new JCheckBox("Bold"); 110 boldCheckBox.addActionListener(listener); JPanel panel = new JPanel(); 113 panel.add(italicCheckBox); 114 panel.add(boldCheckBox); 115 panel.setBorder(new TitledBorder(new EtchedBorder(), "Style")); return panel; 118 } 119

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 120 /** 121 Creates the radio buttons to select the font size the panel containing the radio buttons 123 */ 124 public JPanel createRadioButtons() 125 { 126 smallButton = new JRadioButton("Small"); 127 smallButton.addActionListener(listener); mediumButton = new JRadioButton("Medium"); 130 mediumButton.addActionListener(listener); largeButton = new JRadioButton("Large"); 133 largeButton.addActionListener(listener); 134 largeButton.setSelected(true); 135

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 136 // Add radio buttons to button group ButtonGroup group = new ButtonGroup(); 139 group.add(smallButton); 140 group.add(mediumButton); 141 group.add(largeButton); JPanel panel = new JPanel(); 144 panel.add(smallButton); 145 panel.add(mediumButton); 146 panel.add(largeButton); 147 panel.setBorder(new TitledBorder(new EtchedBorder(), "Size")); return panel; 150 }

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 152 /** 153 Gets user choice for font name, style, and size 154 and sets the font of the text sample. 155 */ 156 public void setSampleFont() 157 { 158 // Get font name 159 String facename 160 = (String) facenameCombo.getSelectedItem(); // Get font style int style = 0; 165 if (italicCheckBox.isSelected()) 166 { 167 style = style + Font.ITALIC; 168 } 169 if (boldCheckBox.isSelected()) 170 { 171 style = style + Font.BOLD; 172 } 173

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/choice/FontViewerFrame.java (cont.) 174 // Get font size int size = 0; final int SMALL_SIZE = 24; 179 final int MEDIUM_SIZE = 36; 180 final int LARGE_SIZE = 48; if (smallButton.isSelected()) { size = SMALL_SIZE; } 183 else if (mediumButton.isSelected()) { size = MEDIUM_SIZE; } 184 else if (largeButton.isSelected()) { size = LARGE_SIZE; } // Set font of text field sampleField.setFont(new Font(facename, style, size)); 189 sampleField.repaint(); 190 } 191 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.8 What is the advantage of a JComboBox over a set of radio buttons? What is the disadvantage? Answer: If you have many options, a set of radio buttons takes up a large area. A combo box can show many options without using up much space. But the user cannot see the options as easily.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.9 Why do all user interface components in the FontViewerFrame class share the same listener? Answer: When any of the component settings is changed, the program simply queries all of them and updates the label.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check Why was the combo box placed inside a panel? What would have happened if it had been added directly to the control panel? Answer: To keep it from growing too large. It would have grown to the same width and height as the two panels below it.

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How To 17.1 Laying Out a User Interface Step 1: Make a sketch of your desired component layout

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How To 17.1 Laying Out a User Interface (cont.) Step 2: Find groupings of adjacent components with the same layout

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How To 17.1 Laying Out a User Interface (cont.) Step 3: Identify layouts for each group Step 4: Group the groups together Step 5: Write the code to generate the layout

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. GUI Builder

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Menus A frame contains a menu bar The menu bar contains menus A menu contains submenus and menu items

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Menu Items Add menu items and submenus with the add method: JMenuItem fileExitItem = new JMenuItem("Exit"); fileMenu.add(fileExitItem); A menu item has no further submenus Menu items generate action events Add a listener to each menu item: fileExitItem.addActionListener(listener); Add action listeners only to menu items, not to menus or the menu bar

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A Sample Program Builds up a small but typical menu Traps action events from menu items To keep program readable, use a separate method for each menu or set of related menus createFaceItem : creates menu item to change the font face createSizeItem createStyleItem

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2.java 1 import javax.swing.JFrame; 2 3 /** 4 This program uses a menu to display font effects. 5 */ 6 public class FontViewer2 7 { 8 public static void main(String[] args) 9 { 10 JFrame frame = new FontViewer2Frame(); 11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 12 frame.setVisible(true); 13 } 14 } 15

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java 1 import java.awt.BorderLayout; 2 import java.awt.Font; 3 import java.awt.GridLayout; 4 import java.awt.event.ActionEvent; 5 import java.awt.event.ActionListener; 6 import javax.swing.ButtonGroup; 7 import javax.swing.JButton; 8 import javax.swing.JCheckBox; 9 import javax.swing.JComboBox; 10 import javax.swing.JFrame; 11 import javax.swing.JLabel; 12 import javax.swing.JMenu; 13 import javax.swing.JMenuBar; 14 import javax.swing.JMenuItem; 15 import javax.swing.JPanel; 16 import javax.swing.JRadioButton; 17 import javax.swing.border.EtchedBorder; 18 import javax.swing.border.TitledBorder; 19

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 20 /** 21 This frame has a menu with commands to change the font 22 of a text sample. 23 */ 24 public class FontViewer2Frame extends JFrame 25 { 26 private static final int FRAME_WIDTH = 300; 27 private static final int FRAME_HEIGHT = 400; private JLabel sampleField; 30 private String facename; 31 private int fontstyle; 32 private int fontsize; 33

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 34 /** 35 Constructs the frame. 36 */ 37 public FontViewer2Frame() 38 { 39 // Construct text sample 40 sampleField = new JLabel("Big Java"); 41 add(sampleField, BorderLayout.CENTER); // Construct menu 44 JMenuBar menuBar = new JMenuBar(); 45 setJMenuBar(menuBar); 46 menuBar.add(createFileMenu()); 47 menuBar.add(createFontMenu()); facename = "Serif"; 50 fontsize = 24; 51 fontstyle = Font.PLAIN; setSampleFont(); 54 setSize(FRAME_WIDTH, FRAME_HEIGHT); 55 } 56

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 57 /** 58 Creates the File menu. the menu 60 */ 61 public JMenu createFileMenu() { 64 JMenu menu = new JMenu("File"); 65 menu.add(createFileExitItem()); 66 return menu; 67 } 68

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 69 /** 70 Creates the File->Exit menu item and sets its action listener. the menu item 72 */ 73 public JMenuItem createFileExitItem() 74 { 75 JMenuItem item = new JMenuItem("Exit"); 76 class MenuItemListener implements ActionListener 77 { 78 public void actionPerformed(ActionEvent event) 79 { 80 System.exit(0); 81 } 82 } 83 ActionListener listener = new MenuItemListener(); 84 item.addActionListener(listener); 85 return item; 86 } 87

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 88 /** 89 Creates the Font submenu. the menu 91 */ 92 public JMenu createFontMenu() 93 { 94 JMenu menu = new JMenu("Font"); 95 menu.add(createFaceMenu()); 96 menu.add(createSizeMenu()); 97 menu.add(createStyleMenu()); 98 return menu; 99 } 100

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 101 /** 102 Creates the Face submenu. the menu 104 */ 105 public JMenu createFaceMenu() 106 { 107 JMenu menu = new JMenu("Face"); 108 menu.add(createFaceItem("Serif")); 109 menu.add(createFaceItem("SansSerif")); 110 menu.add(createFaceItem("Monospaced")); 111 return menu; 112 } 113

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 114 /** 115 Creates the Size submenu. the menu 117 */ 118 public JMenu createSizeMenu() 119 { 120 JMenu menu = new JMenu("Size"); 121 menu.add(createSizeItem("Smaller", -1)); 122 menu.add(createSizeItem("Larger", 1)); 123 return menu; 124 } 125

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 126 /** 127 Creates the Style submenu. the menu 129 */ 130 public JMenu createStyleMenu() 131 { 132 JMenu menu = new JMenu("Style"); 133 menu.add(createStyleItem("Plain", Font.PLAIN)); 134 menu.add(createStyleItem("Bold", Font.BOLD)); 135 menu.add(createStyleItem("Italic", Font.ITALIC)); 136 menu.add(createStyleItem("Bold Italic", Font.BOLD Font.ITALIC)); 138 return menu; 139 } 140

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 141 /** 142 Creates a menu item to change the font face and set its action listener. name the name of the font face the menu item 145 */ 146 public JMenuItem createFaceItem(final String name) 147 { 148 JMenuItem item = new JMenuItem(name); 149 class MenuItemListener implements ActionListener 150 { 151 public void actionPerformed(ActionEvent event) 152 { 153 facename = name; 154 setSampleFont(); 155 } 156 } 157 ActionListener listener = new MenuItemListener(); 158 item.addActionListener(listener); 159 return item; 160 } 161

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 162 /** 163 Creates a menu item to change the font size 164 and set its action listener. name the name of the menu item ds the amount by which to change the size the menu item 168 */ 169 public JMenuItem createSizeItem(String name, final int ds) 170 { 171 JMenuItem item = new JMenuItem(name); 172 class MenuItemListener implements ActionListener 173 { 174 public void actionPerformed(ActionEvent event) 175 { 176 fontsize = fontsize + ds; 177 setSampleFont(); 178 } 179 } 180 ActionListener listener = new MenuItemListener(); 181 item.addActionListener(listener); 182 return item; 183 } 184

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 185 /** 186 Creates a menu item to change the font style 187 and set its action listener. name the name of the menu item style the new font style the menu item 191 */ 192 public JMenuItem createStyleItem(String name, final int style) 193 { 194 JMenuItem item = new JMenuItem(name); 195 class MenuItemListener implements ActionListener 196 { 197 public void actionPerformed(ActionEvent event) 198 { 199 fontstyle = style; 200 setSampleFont(); 201 } 202 } 203 ActionListener listener = new MenuItemListener(); 204 item.addActionListener(listener); 205 return item; 206 } 207

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/menu/FontViewer2Frame.java (cont.) 208 /** 209 Sets the font of the text sample. 210 */ 211 public void setSampleFont() 212 { 213 Font f = new Font(facename, fontstyle, fontsize); 214 sampleField.setFont(f); 215 sampleField.repaint(); 216 } 217 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check Why do JMenu objects not generate action events? Answer: When you open a menu, you have not yet made a selection. Only JMenuItem objects correspond to selections.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check Why is the name parameter in the createFaceItem method declared as final ? Answer: The parameter variable is accessed in a method of an inner class.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Exploring the Swing Documentation For more sophisticated effects, explore the Swing documentation The documentation can be quite intimidating at first glance Next example will show how to use the documentation to your advantage

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Example: A Color Viewer It should be fun to mix your own colors, with a slider for the red, green, and blue values

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Example: A Color Viewer How do you know if there is a slider? Buy a book that illustrates all Swing components Run sample application included in the JDK that shows off all Swing components Look at the names of all of the classes that start with J JSlider seems like a good candidate Next, ask a few questions: How do I construct a JSlider ? How can I get notified when the user has moved it? How can I tell to which value the user has set it? After mastering sliders, you can find out how to set tick marks, etc.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. The SwingSet Demo

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Example: A Color Viewer There are over 50 methods in JSlider class and over 250 inherited methods Some method descriptions look scary: Develop the ability to separate fundamental concepts from ephemeral minutiae

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How do I construct a JSlider ? Look at the Java version 6 API documentation There are six constructors for the JSlider class Learn about one or two of them Strike a balance somewhere between the trivial and the bizarre Too limited: public JSlider() Creates a horizontal slider with the range 0 to 100 and an initial value of 50

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How Do I Construct a Jslider ? Bizarre: public JSlider(BoundedRangeModel brm) Creates a horizontal slider using the specified BoundedRangeModel Useful: public JSlider(int min, int max, int value) Creates a horizontal slider using the specified min, max, and value

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How Can I Get Notified When the User Has Moved a JSlider ? There is no addActionListener method There is a method: public void addChangeListener(ChangeListener l) Click on the ChangeListener link to learn more It has a single method: void stateChanged(ChangeEvent e) Apparently, method is called whenever user moves the slider What is a ChangeEvent ? It inherits getSource method from superclass EventObject getSource : Tells us which component generated this event

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. How Can I Tell To Which Value the User Has Set a JSlider ? Now we have a plan: 1.Add a change event listener to each slider 2.When slider is changed, stateChanged method is called 3.Find out the new value of the slider 4.Recompute color value 5.Repaint color panel Need to get the current value of the slider Look at all the methods that start with get; you find: public int getValue() Returns the slider’s value

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. The Components of the ColorViewerFrame

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Classes of the Color Viewer Program

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/slider/ColorViewer.java 1 import javax.swing.JFrame; 2 3 public class ColorViewer 4 { 5 public static void main(String[] args) 6 { 7 ColorViewerFrame frame = new ColorViewerFrame(); 8 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 9 frame.setVisible(true); 10 } 11 } 12

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/slider/ColorViewerFrame.java 1 import java.awt.BorderLayout; 2 import java.awt.Color; 3 import java.awt.GridLayout; 4 import javax.swing.JFrame; 5 import javax.swing.JLabel; 6 import javax.swing.JPanel; 7 import javax.swing.JSlider; 8 import javax.swing.event.ChangeListener; 9 import javax.swing.event.ChangeEvent; public class ColorViewerFrame extends JFrame 12 { 13 private static final int FRAME_WIDTH = 300; 14 private static final int FRAME_HEIGHT = 400; private JPanel colorPanel; 17 private JSlider redSlider; 18 private JSlider greenSlider; 19 private JSlider blueSlider; 20

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/slider/ColorViewerFrame.java (cont.) 21 public ColorViewerFrame() 22 { 23 colorPanel = new JPanel(); add(colorPanel, BorderLayout.CENTER); 26 createControlPanel(); 27 setSampleColor(); 28 setSize(FRAME_WIDTH, FRAME_HEIGHT); 29 } public void createControlPanel() 32 { 33 class ColorListener implements ChangeListener 34 { 35 public void stateChanged(ChangeEvent event) 36 { 37 setSampleColor(); 38 } 39 } ChangeListener listener = new ColorListener(); 42

Continued Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/slider/ColorViewerFrame.java (cont.) 43 redSlider = new JSlider(0, 255, 255); 44 redSlider.addChangeListener(listener); greenSlider = new JSlider(0, 255, 175); 47 greenSlider.addChangeListener(listener); blueSlider = new JSlider(0, 255, 175); 50 blueSlider.addChangeListener(listener); JPanel controlPanel = new JPanel(); 53 controlPanel.setLayout(new GridLayout(3, 2)); controlPanel.add(new JLabel("Red")); 56 controlPanel.add(redSlider); controlPanel.add(new JLabel("Green")); 59 controlPanel.add(greenSlider); controlPanel.add(new JLabel("Blue")); 62 controlPanel.add(blueSlider); add(controlPanel, BorderLayout.SOUTH); 65 } 66

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/slider/ColorViewerFrame.java (cont.) 67 /** 68 Reads the slider values and sets the panel to 69 the selected color. 70 */ 71 public void setSampleColor() 72 { 73 // Read slider values int red = redSlider.getValue(); 76 int green = greenSlider.getValue(); 77 int blue = blueSlider.getValue(); // Set panel background to selected color colorPanel.setBackground(new Color(red, green, blue)); 82 colorPanel.repaint(); 83 } 84 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check Suppose you want to allow users to pick a color from a color dialog box. Which class would you use? Look in the API documentation. Answer: JColorChooser.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check Why does a slider emit change events and not action events? Answer: Action events describe one-time changes, such as button clicks. Change events describe continuous changes.