55
Getting Input

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

Embed Size (px)

Citation preview

Page 1: 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

Getting Input

Page 2: 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

Text Fields

• A text field is a box that the user can type in

• Use the JTextField classJTextField tf1 = new JTextField(15);

• 15 is the field size in charactersJTextField tf1 = new JTextField(“billy”,15);

• “billy” is the default text in the field

Page 3: 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

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.

Page 4: 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

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)

Page 5: 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

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.

Page 6: 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

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

Page 7: 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

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.

Page 8: 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

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());

Page 9: 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

Numeric Data (cont’d)

• a parseDouble() method is also available

• [See also parseShort(), parseLong(), parseByte(), parseFloat()]

Page 10: 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

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.

Page 11: 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

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

Page 12: 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

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;

}

}

Page 13: 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

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.

Page 14: 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

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…

Page 15: 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

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(); }}

Page 16: 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

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.

Page 17: 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

TextArea

Page 18: 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

Text Area

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

Page 19: 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

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()

Page 20: 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

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.

Page 21: 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

Scroll Bars

JScrollPane scroll = new JscrollPane(myBlahBlahBlah, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JscrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

Page 22: 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

Check Boxes

Page 23: 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

Check Boxes

• Boxes that you can click• Allow multiple selections. (You can select

more than one at a time.• Cf radio boxes (coming up)

Page 24: 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

Check Boxes -constructors

• Use the JcheckBox class• Constructors:• JCheckBox() - unchecked checkbox

w/out associated text• JCheckBox(String text) -

unchecked checkbox with an associated “label”

Page 25: 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

Check Boxes - constructors

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

Page 26: 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

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?

Page 27: 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

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)

Page 28: 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

Radio Buttons

Page 29: 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

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

Page 30: 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

Radio Buttons - constructors

• JRadioButton() - button w/out text• JRadioButton(String text) -

button with associated “label” text

Page 31: 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

Radio Buttons - methods

• void actionListener(ActionListener listener)

• Boolean isSelected()• void setSelected(boolean value)

• void setText()

Page 32: 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

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

Page 33: 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

Button Groups

small = new JRadioButton(“Small”);

ButtonGroup group1 = new ButtonGroup();

group1.add(small);group1.add(medium);group1.add(large);

Page 34: 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

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.

Page 35: 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

Sliders

Page 36: 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

Sliders

• ConstructorsJSlider() //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

Page 37: 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

Sliders

• Methodsvoid 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)

Page 38: 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

Sliders

void setPaintLabels(boolean value) // show tick labels, if true

void setPaintTicks (boolean value) //must be true or no paint ticks will be shown

Page 39: 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

Sliders - creation

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

Page 40: 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

Sliders - Listenerspublic 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); }}

Page 41: 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

Sliders - Listenersprivate 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

Page 42: 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

Sliders - Listeners

slider.addChangeListener(new SliderListener());

Page 43: 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

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.

Page 44: 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

JComboBox - constructors

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

Page 45: 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

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

Page 46: 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

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

Page 47: 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

JComboBox – add items

JComboBox combo1 = new JComboBox();

combo1.addItem(“Bashful”);combo1.addItem(“Grumpy”);combo1.addItem(“Doc”);combo1.addItem(“Dopey”);

Page 48: 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

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); }}

Page 49: 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

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.

Page 50: 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

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.

Page 51: 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

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).

Page 52: 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

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

Page 53: 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

JList - methods

int getSelectedIndex() //returns index of 1st 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 1st selected item of null if no item selected.

Object[] getSelectedValues() //returns an array w/all selected items

Page 54: 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

JList - methods

boolean isSelected(int index) //returns true/false if the item @ index is selected

void setVisibleRowCount (int count) //sets # of rows displayed

Page 55: 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

JList Creation Algorithm

• Call a constructor• Call setVisibleRowCount() to set #

of rows you wish to be visible• Add a scroll pane