Download presentation
Presentation is loading. Please wait.
Published byJesse Barnett Modified over 9 years ago
1
Getting Input
2
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
3
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.
4
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)
5
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.
6
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
7
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.
8
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());
9
Numeric Data(cont’d) a parseDouble() method is also available [See also parseShort(), parseLong(), parseByte(), parseFloat() ]
10
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.
11
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
12
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; }
13
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.
14
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…
15
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(); }
16
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.
17
TextArea
18
We instantiate it like this: JTextArea myBlahBlahBlah = new JtextArea();
19
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()
20
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.
21
Scroll Bars JScrollPane scroll = new JscrollPane(myBlahBlahBlah, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JscrollPane.HORIZONTAL_SCROLLBAR_AS_NEE DED);
22
Check Boxes
23
Boxes that you can click Allow multiple selections. (You can select more than one at a time. Cf radio boxes (coming up)
24
Check Boxes -constructors Use the JcheckBox class Constructors: JCheckBox() - unchecked checkbox w/out associated text JCheckBox(String text) - unchecked checkbox with an associated “label”
25
Check Boxes - constructors JCheckBox(String text, boolean selected) - checkbox with associated “label” and the checkbox is selected/unselected according to value of selected.
26
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?
27
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)
28
Radio Buttons
29
Only one can be selected at a time. Selecting one toggles any other selected button off. cf. check boxes Use the JRadioButton class
30
Radio Buttons - constructors JRadioButton() - button w/out text JRadioButton(String text) - button with associated “label” text
31
Radio Buttons - methods void actionListener(ActionListener listener) Boolean isSelected() void setSelected(boolean value) void setText()
32
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
33
Button Groups small = new JRadioButton(“Small”); ButtonGroup group1 = new ButtonGroup(); group1.add(small); group1.add(medium); group1.add(large);
34
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.
35
Sliders
36
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
37
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)
38
Sliders void setPaintLabels(boolean value) // show tick labels, if true void setPaintTicks (boolean value) //must be true or no paint ticks will be shown
39
Sliders - creation slider = new JSlider(0,50,0); slider.setMajorTickSpacing(10); slider.setMinorTickSpacing(1); slider.setPaintTicks(true); slider.setPaintLabels(true); panel1.add(slider);
40
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); }
41
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
42
Sliders - Listeners slider.addChangeListener(new SliderListener());
43
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.
44
JComboBox - constructors JComboBox() JComboBox(Object[] items) //fills the combo box with items from the array
45
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
46
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
47
JComboBox – add items JComboBox combo1 = new JComboBox(); combo1.addItem(“Bashful”); combo1.addItem(“Grumpy”); combo1.addItem(“Doc”); combo1.addItem(“Dopey”);
48
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); }
49
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.
50
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.
51
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).
52
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
53
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
54
JList - methods boolean isSelected(int index) //returns true/false if the item @ index is selected void setVisibleRowCount (int count) //sets # of rows displayed
55
JList Creation Algorithm Call a constructor Call setVisibleRowCount() to set # of rows you wish to be visible Add a scroll pane
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.