Getting Input. Text Fields A text field is a box that the user can type in Use the JTextField class...

Preview:

Citation preview

Getting Input

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

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

Text Area

• 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_NEEDED);

Check Boxes

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

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

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

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)

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

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

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

JList - methods

boolean isSelected(int index) //returns true/false if the item @ 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

Recommended