Chapter 12: Graphical User Interfaces 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 12 Graphical User Interfaces JAVA.

Slides:



Advertisements
Similar presentations
Chapter 19 – Graphical User Interfaces
Advertisements

Graphical User Interfaces (Part IV)
Graphical User Interfaces, 2D Graphics & Game Programming.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container.
Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Chapter Eighteen: Graphical User Interfaces. Chapter Goals To understand the use of layout managers to arrange user- interface components in a container.
GUI and Event-Driven Programming Recitation – 3/6/2009 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 14 GUI and Event-Driven Programming.
Carnegie Mellon University, MISM1 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann Thread.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Layout Mangers CSC 171 FALL 2001 LECTURE 14. History: The Transistor William Shockley, John Bardeen, and Walter Brattain invent the transfer resistance.
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.
Unit 11 Object-oriented programming: Graphical user interface Jin Sa.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
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.
Adding Graphics to a Frame Application Applets: Can generate drawings by overriding paint Frame: Do not draw directly on a frame. Draw graphics on a JPanel.
Chapter 12 Event Handling. Chapter Goals To understand the Java event model To install action and mouse event listeners To accept input from buttons,
Chapter 14 Graphical User Interfaces. Chapter Goals To use inheritance to customize frames To understand how user-interface components are added to a.
Chapter 17 – Graphical User Interfaces Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
10/24/20151 Java GUI Programming. 10/24/20152 What is a GUI? Java has standard packages for creating custom Graphical User Interfaces Some of the fundamental.
Object-Oriented Programming (Java), Unit 19 Kirk Scott 1.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
Fall 2006Adapded from Java Concepts Companion Slides1 Event Handling Advanced Programming ICOM 4015 Lecture 13 Reading: Java Concepts Chapter 12.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphical User Interface. Chapter Goals To understand the use of layout managers to arrange user- interface components in a container To become familiar.
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 Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
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 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 10: Event Handling 1 Event Handling.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
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 Chapter 10: Event Handling 1 Chapter 10 Event Handling.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
More GUI Components We finish off our examination of GUI components today by looking at a few that we haven’t seen yet –we start off with the JSlider the.
©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 12: Graphical User Interfaces 1 Chapter 12 Graphical User Interfaces.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
GUI Components CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
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)
Graphical User Interface (GUI) Two-Dimensional Graphical Shapes.
GUI Tutorial 2. What did we do last time?  Basic flow  instance variables, set up in ctor, close operation, size, visible  JFrame  Event-driven programming.
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 in 1 Graphical User Interface 3 Nouf Almunyif.
Object-Orientated Analysis, Design and Programming
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Lecture 16 More GUI programming
Chapter 13: Advanced GUIs and Graphics
Chapter 14 Graphical User Interfaces
Chapter 12 Event Handling
Graphical User Interface
CiS 260: App Dev I Chapter 6: GUI and OOD.
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Chapter 12: Graphical User Interfaces 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 1 Chapter 12 Graphical User Interfaces JAVA

Chapter 12: Graphical User Interfaces 2 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 2 Structure Predefined structure –Jbutton –Jpanel –Jframe –contentPane –Container

Chapter 12: Graphical User Interfaces 3 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 3 Figure 1 A Program with Four Buttons contentPane with border layout Panel with flow layout

Chapter 12: Graphical User Interfaces 4 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 4 Layout Management JAVA Swing Add buttons – contentPane.add(upButton, “South”); – contentPane.add(downbutton, “South”); //error Jpanel buttonPanel = new Jpanel(); buttonPanel.add(upButton); buttonPanel.add(downButton); buttonPanel.add(leftButton); buttonPanel.add(rigtButton); contentPane.add(buttonPanel, “South”);

Chapter 12: Graphical User Interfaces 5 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 5 Layout Management Border layout Flow layout Grid layout Build up user interfaces by adding components into containers. The content pane is a container (Jpanel) Content pane (default: border layout) Panel (default: flow layout)

Chapter 12: Graphical User Interfaces 6 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 6 Layout Management Border layout: grows each component to fill all available space in its area. The flow layout leaves each component at its preferred size. The grid layout arranges components in a grid with a fixed number of rows and columns, resizing each of the component.

Chapter 12: Graphical User Interfaces 7 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 7 Border Layout Panel Jpanel panel = new Jpanel(); panel.setLayout(new BorderLayout());

Chapter 12: Graphical User Interfaces 8 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 8 Figure 2 Containers with Separate Layout Managers

Chapter 12: Graphical User Interfaces 9 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 9 Figure 3 The Border Layout Grows Components

Chapter 12: Graphical User Interfaces 10 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 10 Grid Layout Jpanel numberPanel = new Jpanel(); numberPanel.setLayout(new GridLayout(4,3)); numberPanel.add(button7); numberPanel.add(button8); numberPanel.add(button9); numberPanel.add(button4); …

Chapter 12: Graphical User Interfaces 11 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 11 Figure 4 Grid Layout

Chapter 12: Graphical User Interfaces 12 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 12 Buttons When a button is clicked, it sends an action event. You need an action listener. leftButton = new JButton(“Left”); leftButton = new JButton(new ImageIcon(“left.gif”)); leftButton = new(“Left, new ImageIcon(“left.gif”));

Chapter 12: Graphical User Interfaces 13 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 13 Figure 5 Buttons with Labels and Icons

Chapter 12: Graphical User Interfaces 14 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 14 Listener Individual listener upButton =new Jbutton(“UP”); ActionListener listener = new UpListener(); upButton.addActionListener(listener); Jbutton upButton; private class UpListener implements … Unified listener – actionPerformed method –getSource method of the ActionEvent parameter

Chapter 12: Graphical User Interfaces 15 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 15 Program ButtonTest.java import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class ButtonTest { public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setTitle("ButtonTest"); frame.show();

Chapter 12: Graphical User Interfaces 16 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 16 } class ButtonFrame extends JFrame { public ButtonFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH,DEFAULT_FRAME_HEIGHT); addWindowListener(new WindowCloser()); // construct components panel = new RectanglePanel(); JPanel buttonPanel = new JPanel(); ActionListener listener = new DirectionListener(); upButton = new JButton("Up"); upButton.addActionListener(listener);

Chapter 12: Graphical User Interfaces 17 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 17 downButton = new JButton("Down"); downButton.addActionListener(listener); leftButton = new JButton("Left"); leftButton.addActionListener(listener); rightButton = new JButton("Right"); rightButton.addActionListener(listener); // add components to content pane Container contentPane = getContentPane(); contentPane.add(panel, "Center"); buttonPanel.add(upButton); buttonPanel.add(downButton); buttonPanel.add(leftButton); buttonPanel.add(rightButton);

Chapter 12: Graphical User Interfaces 18 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 18 contentPane.add(buttonPanel, "South"); } private RectanglePanel panel; private JButton upButton; private JButton downButton; private JButton leftButton; private JButton rightButton; // inner class definition private class DirectionListener implements ActionListener { public void actionPerformed(ActionEvent event) { // find the button that was clicked Object source = event.getSource();

Chapter 12: Graphical User Interfaces 19 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 19 if (source == upButton) panel.moveRectangle(0, -1); else if (source == downButton) panel.moveRectangle(0, 1); else if (source == leftButton) panel.moveRectangle(-1, 0); else if (source == rightButton) panel.moveRectangle(1, 0); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); }

Chapter 12: Graphical User Interfaces 20 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 20 class RectanglePanel extends JPanel { public RectanglePanel() { rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.draw(rect); }

Chapter 12: Graphical User Interfaces 21 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 21 /** Moves the rectangle and repaints it. The rectangle is moved by multiples of its full width or dx the number of width dy the number of height units */ public void moveRectangle(int dx, int dy) { rect.translate(dx * RECT_WIDTH, dy * RECT_HEIGHT); repaint(); } private Rectangle rect; private static final int RECT_WIDTH = 20; private static final int RECT_HEIGHT = 30; }

Chapter 12: Graphical User Interfaces 22 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 22 Common Errors of the Button Do not identify components by their label text. Forgetting to attach a listener.

Chapter 12: Graphical User Interfaces 23 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 23 Text Components JTextArea class Both JTextField and JTextArea are subclasses of the JTextComponent class. Number of characters – JTextFiled interestRateField = new JTextField(5); Rows and columns –JTextArea resultArea = new JTextArea(10, 40)

Chapter 12: Graphical User Interfaces 24 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 24 Text Components setEditalbe –JTextField result = new JTextField(); – result.setEditable(false); setFont method

Chapter 12: Graphical User Interfaces 25 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 25 Figure 6 A Frame with a Text Area and a Text Field

Chapter 12: Graphical User Interfaces 26 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 26 Program TextTest.java import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.StringTokenizer; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; public class TextTest { public static void main(String[] args) { TextFrame frame = new TextFrame();

Chapter 12: Graphical User Interfaces 27 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 27 frame.setTitle("TextTest"); frame.show(); } class TextFrame extends JFrame { public TextFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT); addWindowListener(new WindowCloser()); // construct components inputArea = new JTextArea(); resultField = new JTextField(20); resultField.setEditable(false);

Chapter 12: Graphical User Interfaces 28 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 28 calcButton = new JButton("Calculate"); calcButton.addActionListener(new ButtonListener()); // add components to content pane Container contentPane = getContentPane(); contentPane.add(inputArea, "Center"); // arrange the label and text field in a panel JPanel resultPanel = new JPanel(); resultPanel.add(new JLabel("Average:")); resultPanel.add(resultField); // place the button in a panel JPanel buttonPanel = new JPanel(); buttonPanel.add(calcButton); // stack up these two panels in another panel

Chapter 12: Graphical User Interfaces 29 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 29 JPanel southPanel = new JPanel(); southPanel.setLayout(new GridLayout(2, 1)); southPanel.add(resultPanel); southPanel.add(buttonPanel); contentPane.add(southPanel, "South"); } /** Reads numbers from a string that contains a sequence of floating-point numbers separated by white input the string containing the the numbers that were found in the string */ public static double[] getData(String input) { StringTokenizer tokenizer = new StringTokenizer(input); double[] data = new double[tokenizer.countTokens()]; for (int i = 0; i < data.length; i++) data[i] = Double.parseDouble(tokenizer.nextToken()); return data;

Chapter 12: Graphical User Interfaces 30 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 30 } /** Computes the average of an array of floating-point data the numbers to the average, or 0 if the array was empty */ public static double average(double[] data) { if (data.length == 0) return 0; double sum = 0; for (int i = 0; i < data.length; i++) sum = sum + data[i]; return sum / data.length; } private JTextArea inputArea; private JTextField resultField; private JButton calcButton;

Chapter 12: Graphical User Interfaces 31 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 31 private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { // get user input from text area double[] data = getData(inputArea.getText()); // compute average and display in result field double avg = average(data); resultField.setText("” + avg); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); }

Chapter 12: Graphical User Interfaces 32 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 32 Choices Radio Buttons (mutually exclusive) Check boxes (not mutually exclusive) Combo Boxes

Chapter 12: Graphical User Interfaces 33 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 33 Figure 7 A Combo Box, Radio Buttons, and Check Boxes

Chapter 12: Graphical User Interfaces 34 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 34 Figure 8 An Opened Combo Box

Chapter 12: Graphical User Interfaces 35 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 35 Program ChoiceTest.java import java.awt.Container; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.border.EtchedBorder; import javax.swing.border.TitledBorder;

Chapter 12: Graphical User Interfaces 36 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 36 public class ChoiceTest { public static void main(String[] args) { ChoiceFrame frame = new ChoiceFrame(); frame.setTitle("ChoiceTest"); frame.show(); } class ChoiceFrame extends JFrame { public ChoiceFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT); addWindowListener(new WindowCloser()); // construct components

Chapter 12: Graphical User Interfaces 37 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 37 sampleField = new JTextField ("Computing Concepts with Java Essentials"); sampleField.setEditable(false); ChoiceListener listener = new ChoiceListener(); facenameCombo = new JComboBox(); facenameCombo.addItem("Serif"); facenameCombo.addItem("SansSerif"); facenameCombo.addItem("Monospaced"); facenameCombo.setEditable(true); facenameCombo.addActionListener(listener); italicCheckBox = new JCheckBox("Italic"); italicCheckBox.addActionListener(listener); boldCheckBox = new JCheckBox("Bold"); boldCheckBox.addActionListener(listener);

Chapter 12: Graphical User Interfaces 38 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 38 smallButton = new JRadioButton("Small"); smallButton.setSelected(true); smallButton.addActionListener(listener); mediumButton = new JRadioButton("Medium"); mediumButton.addActionListener(listener); largeButton = new JRadioButton("Large"); largeButton.addActionListener(listener); // add radio buttons to button group ButtonGroup sizeGroup = new ButtonGroup(); sizeGroup.add(smallButton); sizeGroup.add(mediumButton); sizeGroup.add(largeButton);

Chapter 12: Graphical User Interfaces 39 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 39 // add components to panels JPanel facenamePanel = new JPanel(); facenamePanel.add(facenameCombo); JPanel sizeGroupPanel = new JPanel(); sizeGroupPanel.add(smallButton); sizeGroupPanel.add(mediumButton); sizeGroupPanel.add(largeButton); sizeGroupPanel.setBorder (new TitledBorder(new EtchedBorder(), "Size")); JPanel styleGroupPanel = new JPanel(); styleGroupPanel.add(italicCheckBox); styleGroupPanel.add(boldCheckBox); styleGroupPanel.setBorder (new TitledBorder(new EtchedBorder(), "Style")); // line up component panels

Chapter 12: Graphical User Interfaces 40 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 40 JPanel southPanel = new JPanel(); southPanel.setLayout(new GridLayout(3, 1)); southPanel.add(facenamePanel); southPanel.add(sizeGroupPanel); southPanel.add(styleGroupPanel); // add panels to content pane Container contentPane = getContentPane(); contentPane.add(sampleField, "Center"); contentPane.add(southPanel, "South"); setSampleFont(); } /** Gets user choice for font name, style, and size and sets the font of the text field. */

Chapter 12: Graphical User Interfaces 41 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 41 public void setSampleFont() { // get font name String facename = (String)facenameCombo.getSelectedItem(); // get font style int style = 0; if (italicCheckBox.isSelected()) style = style + Font.ITALIC; if (boldCheckBox.isSelected()) style = style + Font.BOLD; // get font size final int SMALL_SIZE = 12; final int MEDIUM_SIZE = 16; final int LARGE_SIZE = 24;

Chapter 12: Graphical User Interfaces 42 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 42 int size = 0; if (smallButton.isSelected()) size = SMALL_SIZE; else if (mediumButton.isSelected()) size = MEDIUM_SIZE; else if (largeButton.isSelected()) size = LARGE_SIZE; // set font of text field sampleField.setFont(new Font(facename, style, size)); sampleField.repaint(); }

Chapter 12: Graphical User Interfaces 43 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 43 private JTextField sampleField; private JCheckBox italicCheckBox; private JCheckBox boldCheckBox; private JRadioButton smallButton; private JRadioButton mediumButton; private JRadioButton largeButton; private JComboBox facenameCombo; private class ChoiceListener implements ActionListener { public void actionPerformed(ActionEvent event) { setSampleFont(); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); }

Chapter 12: Graphical User Interfaces 44 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 44 Menus Add a listener to each menu item.

Chapter 12: Graphical User Interfaces 45 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 45 Figure 9 Pulldown Menus

Chapter 12: Graphical User Interfaces 46 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 46 Program MenuTest.java import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel;

Chapter 12: Graphical User Interfaces 47 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 47 public class MenuTest { public static void main(String[] args) { MenuFrame frame = new MenuFrame(); frame.setTitle("MenuTest"); frame.show(); } class MenuFrame extends JFrame { public MenuFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT); addWindowListener(new WindowCloser()); // add drawing panel to content pane

Chapter 12: Graphical User Interfaces 48 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 48 panel = new RectanglePanel(); Container contentPane = getContentPane(); contentPane.add(panel, "Center"); // construct menu JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); MenuListener listener = new MenuListener(); newMenuItem = new JMenuItem("New"); fileMenu.add(newMenuItem); newMenuItem.addActionListener(listener);

Chapter 12: Graphical User Interfaces 49 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 49 exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem); exitMenuItem.addActionListener(listener); JMenu editMenu = new JMenu("Edit"); menuBar.add(editMenu); JMenuItem moveMenu = new JMenu("Move"); editMenu.add(moveMenu); upMenuItem = new JMenuItem("Up"); moveMenu.add(upMenuItem); upMenuItem.addActionListener(listener); downMenuItem = new JMenuItem("Down"); moveMenu.add(downMenuItem); downMenuItem.addActionListener(listener);

Chapter 12: Graphical User Interfaces 50 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 50 leftMenuItem = new JMenuItem("Left"); moveMenu.add(leftMenuItem); leftMenuItem.addActionListener(listener); rightMenuItem = new JMenuItem("Right"); moveMenu.add(rightMenuItem); rightMenuItem.addActionListener(listener); randomizeMenuItem = new JMenuItem("Randomize"); editMenu.add(randomizeMenuItem); randomizeMenuItem.addActionListener(listener); } private JMenuItem exitMenuItem; private JMenuItem newMenuItem; private JMenuItem upMenuItem; private JMenuItem downMenuItem; private JMenuItem leftMenuItem; private JMenuItem rightMenuItem;

Chapter 12: Graphical User Interfaces 51 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 51 private JMenuItem randomizeMenuItem; private RectanglePanel panel; private class MenuListener implements ActionListener { public void actionPerformed(ActionEvent event) { // find the menu that was selected Object source = event.getSource(); if (source == exitMenuItem) System.exit(0); else if (source == newMenuItem) panel.reset(); else if (source == upMenuItem) panel.moveRectangle(0, -1); else if (source == downMenuItem) panel.moveRectangle(0, 1); else if (source == leftMenuItem) panel.moveRectangle(-1, 0);

Chapter 12: Graphical User Interfaces 52 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 52 else if (source == rightMenuItem) panel.moveRectangle(1, 0); else if (source == randomizeMenuItem) panel.randomize(); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); } class RectanglePanel extends JPanel { public RectanglePanel() { rect = new Rectangle(0, 0, RECT_WIDTH, RECT_HEIGHT); }

Chapter 12: Graphical User Interfaces 53 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 53 public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.draw(rect); } /** Resets the rectangle to the top left corner. */ public void reset() { rect.setLocation(0, 0); repaint(); }

Chapter 12: Graphical User Interfaces 54 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 54 /** Moves the rectangle to a random position. */ public void randomize() { Random generator = new Random(); rect.setLocation(generator.nextInt(getWidth()), generator.nextInt(getHeight())); repaint(); }

Chapter 12: Graphical User Interfaces 55 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 55 /** Moves the rectangle and repaints it. The rectangle is moved by multiples of its full width or dx the number of width dy the number of height units */ public void moveRectangle(int dx, int dy) { rect.translate(dx * RECT_WIDTH, dy * RECT_HEIGHT); repaint(); } private Rectangle rect; private static int RECT_WIDTH = 20; private static int RECT_HEIGHT = 30; }

Chapter 12: Graphical User Interfaces 56 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 56 Figure 10 A Color Mixer

Chapter 12: Graphical User Interfaces 57 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 57 Program SliderTest.java import java.awt.Color; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.event.ChangeListener; import javax.swing.event.ChangeEvent;

Chapter 12: Graphical User Interfaces 58 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 58 public class SliderTest { public static void main(String[] args) { SliderFrame frame = new SliderFrame(); frame.setTitle("SliderTest"); frame.show(); } class SliderFrame extends JFrame { public SliderFrame() { final int DEFAULT_FRAME_WIDTH = 300; final int DEFAULT_FRAME_HEIGHT = 300; setSize(DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT); addWindowListener(new WindowCloser()); // construct components colorPanel = new JPanel();

Chapter 12: Graphical User Interfaces 59 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 59 ColorListener listener = new ColorListener(); redSlider = new JSlider(0, 100, 100); redSlider.addChangeListener(listener); greenSlider = new JSlider(0, 100, 70); greenSlider.addChangeListener(listener); blueSlider = new JSlider(0, 100, 70); blueSlider.addChangeListener(listener); // fill content pane JPanel southPanel = new JPanel(); southPanel.setLayout(new GridLayout(3, 2)); southPanel.add(new JLabel("Red", SwingConstants.RIGHT));

Chapter 12: Graphical User Interfaces 60 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 60 southPanel.add(redSlider); southPanel.add(new JLabel("Green", SwingConstants.RIGHT)); southPanel.add(greenSlider); southPanel.add(new JLabel("Blue", SwingConstants.RIGHT)); southPanel.add(blueSlider); Container contentPane = getContentPane(); contentPane.add(colorPanel, "Center"); contentPane.add(southPanel, "South"); setSampleColor(); } /** Reads the slider values and sets the panel to the selected color. */

Chapter 12: Graphical User Interfaces 61 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 61 public void setSampleColor() { // read slider values float red = 0.01F * redSlider.getValue(); float green = 0.01F * greenSlider.getValue(); float blue = 0.01F * blueSlider.getValue(); // set panel background to selected color colorPanel.setBackground(new Color(red, green, blue)); colorPanel.repaint(); } private JPanel colorPanel; private JSlider redSlider; private JSlider greenSlider; private JSlider blueSlider;

Chapter 12: Graphical User Interfaces 62 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 62 private class ColorListener implements ChangeListener { public void stateChanged(ChangeEvent event) { setSampleColor(); } private class WindowCloser extends WindowAdapter { public void windowClosing(WindowEvent event) { System.exit(0); }

Chapter 12: Graphical User Interfaces 63 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e 63 Homework P12.3 Calculator with + - * / operations Use grid layout and text.