Getting Input. Text Fields A text field is a box that the user can type in Use the JTextField class JTextField tf1 = new JTextField(15); 15 is the field.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 17 Creating User Interfaces.
Advertisements

More on GUI We wrap up our examination of Java GUI programming by looking at several other components and their listeners – The components all come from.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 16 Creating User Interfaces.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L04 (Chapter 15) Creating.
1 Creating User Interfaces. 2 Motivations A graphical user interface (GUI) makes a system user-friendly and easy to use. Creating a GUI requires creativity.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
GUI and Event-Driven Programming Part 2. Event Handling An action involving a GUI object, such as clicking a button, is called an event. The mechanism.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
GUI Programming in Java: Event Handling & More Components Corresponds with Chapter 14, Chapter 15.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
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 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 13 Creating User.
Creating User Interfaces F JComponent F JButton F JLabel F JTextField F JTextArea F JComboBox F JList F JCheckBox F JRadioButton F Dialogs.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Java Swing. Swing is a set of classes that provides more powerful and flexible components than are possible with the AWT. In addition to the familiar.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 19.1 Test-Driving the Shipping Hub Application.
Dale Roberts GUI Programming using Java - GUI Components Dale Roberts, Lecturer Computer Science, IUPUI Department of Computer.
{ Dating Service ActionHandler Listener class details.
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 15 Creating User.
CHAPTER:07 JAVA IDE PROGRAMMING-II Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Java GUI. Overview The ”idea” The ”idea” The Components The Components Listeners Listeners The Program The Program Interface Eventlistener Interface Eventlistener.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 – Graphical User Interfaces Java Foundations: Introduction to Programming.
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.
Chapter 11 - A GUI Interacting With a Problem Domain Class1 Chapter 11 A GUI Interacting With a Problem Domain Class 11.
Creating User Interfaces Chapter 13 CSCI CSCI 1302 – Creating User Interfaces2 Outline Introduction Common Features of Swing GUI Components Buttons.
Software Construction LAB 08 Java Programming with SWING GUI Builder.
GUI Components CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Java Programming, Second Edition Chapter Thirteen Understanding Swing Components.
Copyright © Curt Hill More Widgets In Abstract Window Toolbox.
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.
Creating a GUI Class An example of class design using inheritance and interfaces.
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,
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
 Figure illustrates a hierarchy containing many event classes from the package java.awt.event.  Used with both AWT and Swing components.  Additional.
Java Swing Controls. JButton One of the most commonly used swing component is Push Button or simply button which is created through JButton class of Swing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
TENTH LECTURE Event and listener. Events and Listeners An event can be defined as a type of signal to the program that something has happened. The event.
Dept. of CSIE, National University of Tainan 10/21/2012 Working with Swing.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Dental Payment Application.
GUIs & Event-Driven Programming Chapter 11 Review.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CSE 205 Exam 2 Review By Cheri Thompson and Katherine Kincade.
GUIs and Events Rick Mercer.
A First Look at GUI Applications Radio Buttons and Check Boxes
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
Chapter 7 Creating User Interfaces
Chapter 17 Creating User Interfaces
Chapter 17 Creating User Interfaces
Presentation transcript:

Getting Input

Text Fields A text field is a box that the user can type in Use the JTextField class JTextField tf1 = new JTextField(15); 15 is the field size in characters JTextField tf1 = new JTextField(“billy”,15); “billy” is the default text in the field

Labels Text fields usually have labels that are associated with them. JLabel jl1 = new Jlabel(“Enter your name: “); The label indicates the appropriate use for the text box.

Getting the Data We use the getText() method in our listener to retrieve the data. There’s a corresponding setText() method if we need it. Let’s look at some source code: Namer.java in the handout folder. –(courtesy of Java for Dummies)

Things to note Different setup than we’re used to: –main method in the class –the class implements the listener as an inner class within itself at line 38 –this gives the listener access to the private members of the containing class line 12: the text field is a class variable so both the constructor and listener class have access to it.

Things to note (cont’d) line 25: a label tells the user what data to put in the text field line 27: specifies the length of the text field line 46: uses the getText() method to retrieve the data entered by the user and store it in a string variable

Things to note (cont’d) line 47: checks to make sure that at least some data was entered by the user. line 61: the text field calls requestFocus() to move the focus back to itself. Otherwise the focus would remain on the button and the user would have to tab back to the text field.

Numeric Data The data returned by getText() is String data. If we need to use it numerically, we need to convert it using a wrapper class. int count = Integer.parseInt(textCount.getText());

Numeric Data(cont’d) a parseDouble() method is also available [See also parseShort(), parseLong(), parseByte(), parseFloat() ]

Numeric Data (cont’d) If the data retrieved by getText() can’t be converted (e.g. it’s a character) then a NumberFormatException is thrown. This causes a run-time error and your program crashes. Oops.

Numeric Data (cont’d) So, it’s a good idea to test the retrived data before converting it. We can use the try…catch construct to deal with exceptions Let’s look at an example

private boolean isInt(JTextField f, String msg) { try { Integer.parseInt(f.getText()); return true; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(f,”Entry Error”, msg, JOptionPane.ERROR_MESSAGE); f.requestFocus(); return false; }

try…catch Works (sort of) like an if…else if no exception is generated (e/thing went OK and the retrieved data was appropriate) the statements associated with the try are executed and the statements under the catch are skipped.

try…catch (cont’d) Otherwise, if an exception was generated and it matches the one specified in the catch ( NumberFormatException ) the statements in the catch are executed. This code “catches” the exception and prevents your program from crashing. So our code could look like this…

public void actionPerformed(ActionEvent e) { if (e.getSource() == buttonOK) { if (isInt(textCount, “You must enter an Integer”)) { JOptionPane.showMessageDialog(Number.this, “You entered “ + Integer.parseInt(textCount.getText()), “Your Number”, JOptionPane.INFORMATION_MESSAGE); } textCount.requestFocus(); }

You Do Create a GUI with 3 text fields that allow the user to enter three integer values. The GUI should contain a button called “Average” which should calculate the average of the 3 numbers when pressed. The average should be displayed in a 4th text field.

TextArea

We instantiate it like this: JTextArea myBlahBlahBlah = new JtextArea();

Text Area – useful methods void append(String text) int getLineCount() String getText() void setText(String text) void insert(String str, int pos) void requestFocus() void setLineWrap(boolean value) void setWRapStyleWord()

Scroll Bars A text area typically has scroll bars to help the user navigate. My previous example didn't. We add scroll bars by declaring a JscrollPane object and attaching the object to our JtextArea object.

Scroll Bars JScrollPane scroll = new JscrollPane(myBlahBlahBlah, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JscrollPane.HORIZONTAL_SCROLLBAR_AS_NEE DED);

Check Boxes

Boxes that you can click Allow multiple selections. (You can select more than one at a time. Cf radio boxes (coming up)

Check Boxes -constructors Use the JcheckBox class Constructors: JCheckBox() - unchecked checkbox w/out associated text JCheckBox(String text) - unchecked checkbox with an associated “label”

Check Boxes - constructors JCheckBox(String text, boolean selected) - checkbox with associated “label” and the checkbox is selected/unselected according to value of selected.

Check Boxes - methods void addActionListener (ActionListener listener) Boolean isSelected() void setSelected(boolean value) - true sets it, false deselects it. BTW, notice how good method and variable names make it easy to figure out what these elements are supposed to do?

You Do Create a frame for ordering an ice cream cone. The frame should include 3 checkboxes that allow the user to select toppings for the cone: sprinkles, chocolate dipping, or peanuts. The frame should include a text area with scroll bars that allow the user to enter a special order to customize their ice cream cone. The frame should have an OK button. When the button is pressed, a dialog box should appear reporting the toppings selected and the user’s special order. (see Pizza example)

Radio Buttons

Only one can be selected at a time. Selecting one toggles any other selected button off. cf. check boxes Use the JRadioButton class

Radio Buttons - constructors JRadioButton() - button w/out text JRadioButton(String text) - button with associated “label” text

Radio Buttons - methods void actionListener(ActionListener listener) Boolean isSelected() void setSelected(boolean value) void setText()

Radio Buttons - groups What happens if you want more than one set of buttons? You want to have more than one selected button at a time? You need ButtonGroup

Button Groups small = new JRadioButton(“Small”); ButtonGroup group1 = new ButtonGroup(); group1.add(small); group1.add(medium); group1.add(large);

You Do Add a radio button group that lets the use choose a size for their ice cream cone: small, medium or large. Make sure that the size selection is reported in the dialog box that appears when the user clicks OK.

Sliders

Constructors JSlider() //def values of 0 & 100 with slider preset to 50 JSlider (int min, int max) JSlider (int min, int max, int value) // initial, default set to value JSlider (int orientation, int min, int max, int value) // orientation: JSlider.HORIZONTAL or JSlider.VERTICAL

Sliders Methods void addChangeLister(ChangeListener listener) int getValue() //get the current value of the slider knob int setInvert(boolean value) //if true, invert the direction so max value is on the left void setMajorTickSpacing(int value) // set interval for tick marks on the slider. void setMinorTickSpacing (int value)

Sliders void setPaintLabels(boolean value) // show tick labels, if true void setPaintTicks (boolean value) //must be true or no paint ticks will be shown

Sliders - creation slider = new JSlider(0,50,0); slider.setMajorTickSpacing(10); slider.setMinorTickSpacing(1); slider.setPaintTicks(true); slider.setPaintLabels(true); panel1.add(slider);

Sliders - Listeners public void actionPerformed (ActionEvent e) { if(e.getSource() == buttonOK) { int level = slider.getValue(); JOptionPane.showMessageDialog(slider, “Remember, this is for posterity.\n” + “Tell me...how do you feel?”, “Level “ + level, JOptionPane.INFORMATION_MESSAGE); }

Sliders - Listeners private class SliderListener implements ChangeListener { public void stateChanged(ChangeEvent e) { if(slider.getValue() == 50) { JOptionPane.showMessageDialog(slider, “No! Not 50!.”, “The Machine”, JOptionPane.WARNING_MESSAGE } } //ENDs class

Sliders - Listeners slider.addChangeListener(new SliderListener());

Lists We can implement lists for the user to choose from using combo boxes. Combo boxes combine a text box and a list from which the user can pick. The text box can be made editable so that the user can enter an item not already in the list or edit one that is. Make the combo box uneditable if you want to restrict the user's choices.

JComboBox - constructors JComboBox() JComboBox(Object[] items) //fills the combo box with items from the array

JcomboBox - Methods void addActionListener(ActionListener Listener) void addItem(Object item) //adds the item to the list void addItemListener(ItemListener listener) int getSelectedIndex() //returns the index of the selected item Object getSelectedItem() //returns the selected item

JcomboBox - methods Boolean isEditable() //indicates whether or not the text box is editable void setEditable(boolean value) //set to true if you want the user to be able to edit the items

JComboBox – add items JComboBox combo1 = new JComboBox(); combo1.addItem(“Bashful”); combo1.addItem(“Grumpy”); combo1.addItem(“Doc”); combo1.addItem(“Dopey”);

JComboBox - retrieval Public void actionPerformed (ActionEvent e) { if(e.getSource()==buttonOK) { String s=(String)combo1.getSelectedItem(); JOptionPane.showMessageDialog(combo1, “You picked “ + s, “Your favourite”, JOptionPane.INFORMATION_MESSAGE); }

JComboBox - events An event is generated when the user makes a selection in the box. Implement ActionListener and add an actionPerformed method if you need to do this.

You Do Add a combo box to your ice cream GUI that implements a combo box of neighbourhoods Make the combo box editable so that the user can enter their own value besides the ones you provide Add the selected item to your output on the message dialog.

Lists Lists (JList) is different from a combo box. Can be configured to allow multiple choices. Usually use scroll panes. Lists can't be edited. List items can't be changed after creation (without jumping through hoops).

JList - Constructors JList() JList(ListModel list) //the list uses the specified list model JList(Object[] items) //Create the list and fill it with objects from the array

JList - methods int getSelectedIndex() //returns index of 1 st selected item; -1 if no items selected int[] getSelectedIndexes() //returns array of indexes of selected items. (Empty array if no items selected.) Object getSelectedValue() //returns 1 st selected item of null if no item selected. Object[] getSelectedValues() //returns an array w/all selected items

JList - methods boolean isSelected(int index) //returns true/false if the index is selected void setVisibleRowCount (int count) //sets # of rows displayed

JList Creation Algorithm Call a constructor Call setVisibleRowCount() to set # of rows you wish to be visible Add a scroll pane