CSC 222: Computer Programming II

Slides:



Advertisements
Similar presentations
Graphic User Interfaces Layout Managers Event Handling.
Advertisements

Java Swing Recitation – 11/(20,21)/2008 CS 180 Department of Computer Science, Purdue University.
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
IEEM 110 Computing in Industrial Applications Basic User Interface in Java.
Chapter 121 Window Interfaces Using Swing Chapter 12.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
Graphical User Interfaces
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Java Programming Chapter 10 Graphical User Interfaces.
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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington User Interface COMP 112 #30.
Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I.
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.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
CSE 219 Computer Science III Graphical User Interface.
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
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.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
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.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
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 ( 李德成 )
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University *Ref:
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
For (int i = 1; i
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7-2 ( Book Chapter 14) GUI and Event-Driven Programming.
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.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
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.
Graphical User Interface (GUI)
Event Handler Methods Text field Object Responder JAVA AWT Environment: Messages are sent between JAVA Objects Screen Event Notification Press Button.
Frame Windows Application program, not applet Construct and show frame JFrame frame = new JFrame(); *** frame.show(); *** Set default close operation..
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Event Driven (Asynchronous) Programming. Event handling in Unity Subclass a class that contains event handling methods, and then override those methods.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
GUIs and Events Rick Mercer.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
CompSci 230 S Programming Techniques
Graphical User Interfaces
Christopher Budo, Davis Nygren, spencer franks, Luke miller
A First Look at GUI Applications
“Form Ever Follows Function” Louis Henri Sullivan
Java GUI.
Graphical User Interface (pronounced "gooey")
Java Programming: From Problem Analysis to Program Design,
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Course Outcomes of Advanced Java Programming AJP (17625, C603)
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Timer class and inner classes
Chapter 12 Event Handling
Chapter 7-2 (Book Chapter 14)
A Quick Java Swing Tutorial
Advanced Programming in Java
Chapter 7-2 (Book Chapter 14)
Graphical User Interface
Presentation transcript:

CSC 222: Computer Programming II Spring 2005 Java event handling events, event sources, event listeners user interaction with buttons: JFrame, JButton text display with labels: JLabel organizing the interface: JPanel user input with text fields: JTextField layout management: BorderLayout, GridLayout

events & interfaces using BlueJ, the user was in control of execution could create an object, click to call a method, enter parameter values at prompt in standard Java, the main method automates this interaction the statements in the main method specify the sequence of actions to perform it is possible to create a graphical user interface (GUI) to return user control utilize windows, buttons, text boxes, etc. the user can control execution by interacting with these elements events (window drags, button clicks, mouse moves, …) trigger actions when defining an event-driven program, must identify which events are relevant e.g., a button doesn't care whether the mouse moves, only if it clicks

ActionEvent & ActionListerner as we saw with the Timer class, an ActionListener object specifies code that is to be executed when a particular event occurs ActionListener is an interface defined in java.awt.event.ActionListener requires an actionPerformed method if an object is to be controlled by an event, associate an ActionListener with it class Timeout implements ActionListener { public void actionPerformed(ActionEvent event) System.out.println("Sorry, time's up."); System.exit(0); } Timer t = new Timer(TIME_LIMIT, new Timeout());

Buttons the simplest graphical interface element is a button JButton class is defined in javax.swing.JButton when you create a button, must specify text that appears on it JButton button = new JButton("Click me"); the event relevant to a button is being clicked associate an ActionListener with the button to specify what to do when clicked class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) System.out.println("Thanks, I needed that."); } button.addActionListener( new ClickListener() );

Button example import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class ButtonTester { public static final int FRAME_WIDTH = 100; public static final int FRAME_HEIGHT = 60; public static void main(String[] args) JButton button = new JButton("Click me"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) System.out.println("Thanks, I needed that."); } button.addActionListener( new ClickListener() ); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(button); frame.setVisible(true); to be visible & used, a button must be added to a frame (window) JFrame class defined in javax.swing.JFrame setSize sets the dimensions of the frame setDefaultCloseOperation allows user to close frame by clicking on X add puts the button in the frame setVisible makes the frame visible on the screen

Labels & panels the previous example displays text in console window at a click of the button not all that useful – don't want to have to go back and forth from frame to console using a label, the program can write text directly into the frame JLabel class is defined in javax.swing.JLabel when you construct a label, specify its initial value JLabel label = new JLabel("I'm waiting..."); labels are passive objects – they don't react to events but other active elements can change the label text (using setText) JButton button = new JButton("Click me"); class ClickListener implements ActionListener { public void actionPerformed(ActionEvent event) label.setText("Thanks, I needed that!"); } button.addActionListener(new ClickListener());

Label example only one item can be added to a frame import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class LabelTester { public static final int FRAME_WIDTH = 200; public static final int FRAME_HEIGHT = 200; public static void main(String[] args) final JLabel label = new JLabel("I'm waiting..."); JButton button = new JButton("Click me"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) label.setText("Thanks, I needed that!"); } button.addActionListener(new ClickListener()); JPanel panel = new JPanel(); panel.add(button); panel.add(label); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setVisible(true); Label example only one item can be added to a frame if want more than one (e.g., button & label), then group together into a panel JPanel class is defined in javax.swing.JPanel can add multiple objects to a panel then add the panel to the frame

getText / setText previous example was somewhat pointless // IMPORT STATEMENTS OMITTED public class LabelTester { public static final int FRAME_WIDTH = 200; public static final int FRAME_HEIGHT = 200; public static void main(String[] args) final JLabel label = new JLabel("I'm waiting..."); JButton button = new JButton("Click me"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) String text = label.getText(); if (text.equals("I'm waiting for you...")) { label.setText("Thanks!"); } else { label.setText(text + " Thanks again."); button.addActionListener(new ClickListener()); JPanel panel = new JPanel(); panel.add(button); panel.add(label); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setVisible(true); getText / setText previous example was somewhat pointless subsequent clicks produced the same label text (no change) using the getText method, can access the value of a label here, access the label text and append to it on each click for an inner class to access an object from the method, it must be final

Simple application suppose we wanted to generate a lucky number user clicks on a button, lucky number appears below GUI elements: need button to initiate number generation need label to display the number need panel to contain the button & label, frame to display the panel program logic: need to generate random number – Math.random? Die?

import java.awt.event.ActionEvent; . . . import java.util.Random; public class LuckyNumber { public static final int FRAME_WIDTH = 200; public static final int FRAME_HEIGHT = 100; public static final int MAX_NUM = 100; public static void main(String[] args) final Random randGen = new Random(); final JLabel label = new JLabel(""); JButton button = new JButton("Click for Lucky Number"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) label.setText("Your number is " + (randGen.nextInt(MAX_NUM)+1)); } button.addActionListener(new ClickListener()); JPanel panel = new JPanel(); panel.add(button); panel.add(label); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setVisible(true); Random numbers Random class is defined in java.util.Random nextInt method generates a random integer in range [0, parameter) again: randGen must be declared final to allow the inner class to have access can call methods to alter the state of a final object, but can't reassign it

More interesting variant suppose we wanted to generalize the lucky number program instead of generating a lucky number, want to generate a fortune GUI elements: need button, label, panel & frame (as before) program logic: need to store a list of possible fortunes – array of Strings? ArrayList of Strings? need to generate random index, select fortune at that index

// IMPORT STATEMENTS OMITTED public class FortuneCookie { public static final int FRAME_WIDTH = 300; public static final int FRAME_HEIGHT = 100; public static final String[] FORTUNES = {"Live long and prosper", "An apple a day keeps the doctor away.", "Don't take any wooden nickels."}; public static void main(String[] args) final Random randGen = new Random(); final JLabel fortuneLabel = new JLabel(""); JButton button = new JButton("Click for fortune"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) fortuneLabel.setText("FORTUNE: " + FORTUNES[randGen.nextInt(FORTUNES.length)]); } button.addActionListener(new ClickListener()); JPanel panel = new JPanel(); panel.add(button); panel.add(fortuneLabel); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setVisible(true); Random fortunes arrays are handy if you know their contents ahead of time can list explicit contents when declaring/creating

Click counts suppose we wanted to keep a count of the occurrences of some event e.g., display count of number of times mouse has been clicked ATTEMPT: define a counter, have the ActionListener increment & display public static void main(String[] args) { final JLabel textLabel = new JLabel("Number of clicks = 0"); int clickCount = 0; JButton button = new JButton("Click Me"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) clickCount++; textLabel.setText("Number of clicks = " + clickCount); } button.addActionListener(new ClickListener()); . . . PROBLEM? won't work – inner class can only access final values

Click count VERSION 1: could define a Counter class that encapsulates a counter could define a final Counter object, call increment method in ActionListener VERSION 2: could add state to the ActionListener class maintain the counter as a field, can then increment & display the field public static void main(String[] args) { final JLabel textLabel = new JLabel("Number of clicks = 0"); JButton button = new JButton("Click Me"); class ClickListener implements ActionListener private int clickCount; public ClickListener() clickCount = 0; } public void actionPerformed(ActionEvent event) clickCount++; textLabel.setText("Number of clicks = " + clickCount); button.addActionListener(new ClickListener()); . . .

VERSION 3 can access a number label as text // IMPORT STATEMENTS OMITTED public class ClickCounter { public static final int FRAME_WIDTH = 200; public static final int FRAME_HEIGHT = 100; public static void main(String[] args) final JLabel textLabel = new JLabel("Number of clicks = "); final JLabel countLabel = new JLabel("0"); JButton button = new JButton("Click Me"); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) int newCount = Integer.parseInt(countLabel.getText())+1; countLabel.setText(""+newCount); } button.addActionListener(new ClickListener()); JPanel panel = new JPanel(); panel.add(button); panel.add(textLabel); panel.add(countLabel); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setVisible(true); can access a number label as text convert to a number using the Integer.parseFloat method increment and put the number back in the label as text

Multiple buttons // IMPORT STATEMENTS OMITTED public class Quizzer { public static final int FRAME_WIDTH = 200; public static final int FRAME_HEIGHT = 150; public static void main(String[] args) final Random randGen = new Random(); final JLabel questionLabel = new JLabel("Do you like to program?"); final JLabel answerLabel = new JLabel(""); class ClickListener implements ActionListener private String labelMessage; public ClickListener(String msg) labelMessage = msg; } public void actionPerformed(ActionEvent event) answerLabel.setText(labelMessage); JButton yesButton = new JButton("Yes"); yesButton.addActionListener(new ClickListener("Good for you!")); JButton noButton = new JButton("No"); noButton.addActionListener(new ClickListener("Give it some time.")); . . . if multiple buttons appear in a frame, it is common for each to define its own ActionListener if actions to be performed are similar, can have a single class with fields & constructor parameters

text fields & areas Basic GUI elements: labels  output in a frame buttons  user control (i.e., initiating an event) text fields/areas  user input a text field is a single-line box in which the user can enter text JTextField class is defined in javax.swing.JTextField JTextField nameField = new JTextField(FIELD_WIDTH); similar to JLabel, can access contents using getText, String userName = nameField.getText(); textLabel.setText("Hi " + userName + ", nice to meet you."); can even update the contents of a text field using setText but, usually, a label looks better for output

Temperature converter // IMPORT STATEMENTS OMITTED public class TempConverter { public static final int FRAME_WIDTH = 350; public static final int FRAME_HEIGHT = 150; public static final int FIELD_WIDTH = 10; public static double fahrToCelsius(double fahrTemp) return (5.0/9.0) * (fahrTemp - 32); } public static void main(String[] args) final JLabel inputLabel = new JLabel("Enter a temperature in Fahrenheit:"); final JLabel outputLabel = new JLabel(""); final JTextField tempField = new JTextField(FIELD_WIDTH); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) double celsius = fahrToCelsius(Double.parseDouble(tempField.getText())); outputLabel.setText("That's equivalent to " + celsius + " degrees Celsius"); JButton convertButton = new JButton("Convert to Celsius"); convertButton.addActionListener(new ClickListener()); JPanel panel = new JPanel(); panel.add(inputLabel); panel.add(tempField); panel.add(convertButton); panel.add(outputLabel); JFrame frame = new JFrame(); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setVisible(true); Temperature converter

In-class exercise suppose we wanted to allow for temperature conversion either way user can enter temperature in Fahrenheit, convert to Celsius user can enter temperature in Celsius, convert to Fahrenheit what should the frame look like? additional GUI elements? associated functionality?

Layout management so far, we have had limited control over the layout of GUI elements by default, a panel uses flow layout (elements are left-to-right, wrap as needed) sometimes this is sufficient, but sometimes not the java.awt has layout managers that can be used to place elements BorderLayout: specify NORTH, EAST, CENTER, WEST, or SOUTH when add to panel GridLayout: can specify number of rows & columns, then add in order can only place one element in a panel position – if more than one (e.g., label + field), then nest inside an inner panel

Temperature layout import java.awt.BorderLayout; . . . JPanel innerPanel = new JPanel(); innerPanel.add(inputLabel); innerPanel.add(tempField); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(innerPanel, BorderLayout.NORTH); panel.add(convertButton, BorderLayout.CENTER); panel.add(outputLabel, BorderLayout.SOUTH); import java.awt.GridLayout . . . JPanel innerPanel = new JPanel(); innerPanel.add(inputLabel); innerPanel.add(tempField); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 1)); panel.add(innerPanel); panel.add(convertButton); panel.add(outputLabel);

Temperature layout import java.awt.BorderLayout; . . . JPanel innerPanel = new JPanel(); innerPanel.add(inputLabel); innerPanel.add(tempField); JPanel buttonPanel = new JPanel(); buttonPanel.add(convertButton); JPanel outputPanel = new JPanel(); outputPanel.add(outputLabel); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.add(innerPanel, BorderLayout.NORTH); panel.add(buttonPanel, BorderLayout.CENTER); panel.add(outputPanel, BorderLayout.SOUTH); even when there is only one element in a position, can be useful to place in an inner panel keeps the button from filling the space centers the element in the space

In-class exercise use a layout manager to control the layout of your temperature conversion page BorderLayout or GridLayout? nested panels?

Text area a text area is similar to a text field except it has multiple rows JTextArea class is defined in javax.swing.JTextArea JTextArea textArea = new JTextArea(NUM_ROWS, NUM_COLS); can access the contents of a text area using getText can assign a value using setText, or append text using append textArea.setText("Howdy\n"); textArea.append("Do"); can designate a text area to be for output only, or set line wrapping textArea.setEditable(false); textArea.setLineWrap(true); can add a scroll bar using the JScrollPane class JScrollPane scrollPane = new JScrollPane(textArea);

Hailstone sequence public class Hailstone { public static final int FRAME_WIDTH = 350; public static final int FRAME_HEIGHT = 450; public static final int FIELD_WIDTH = 6; public static final int AREA_WIDTH = 20; public static final int AREA_HEIGHT = 30; public static void main(String[] args) final JLabel inputLabel = new JLabel("Enter a starting value:"); final JTextField startField = new JTextField(FIELD_WIDTH); final JTextArea outputArea = new JTextArea(AREA_WIDTH, AREA_HEIGHT); outputArea.setEditable(false); outputArea.setLineWrap(true); JScrollPane outputPane = new JScrollPane(outputArea); class ClickListener implements ActionListener public void actionPerformed(ActionEvent event) int num = Integer.parseInt(startField.getText()); outputArea.setText("" + num + "\n"); while (num != 1) { if (num % 2 == 0) { num = num / 2; } else { num = 3*num + 1; outputArea.append("" + num + "\n"); . . .