You now know how to collect text input from users, but there are many occasions for which you would rather give users a finite set of choices than have them enter the data in a text component. Using a set of buttons or a list of items tells your users what choices they have. (It also saves you the trouble of error checking.) In this section, you learn how to program checkboxes, radio buttons, lists of choices, and sliders.
If you want to collect just a “yes” or “no” input, use a check box component. Check boxes automatically come with labels that identify them. The user usually checks the box by clicking inside it and turns off the check mark by clicking inside the box again. To toggle the check mark, the user can also press the space bar when the focus is in the checkbox. a simple program with two checkboxes, one to turn on or off the italic attribute of a font, and the other for bold face. Note that the second check box has focus, as indicated by the rectangle around the label. Each time the user clicks one of the check boxes, the screen is refreshed, using the new font attributes.
Checkboxes need a label next to them to identify their purpose. You give the label text in the constructor.
You use the setSelected method to turn a checkbox on or off. For example:
The isSelected method then retrieves the current state of each checkbox. It is false if unchecked; true if checked.
When the user clicks on a checkbox, this triggers an action event. As always, you attach an action listener to the checkbox. In our program, the two checkboxes share the same action listener.
The action Performed method queries the state of the bold and italic check boxes and sets the font of the panel to plain, bold, italic, or both bold and italic.
In the previous example, the user could check either, both, or neither of the two checkboxes. In many cases, we want to require the user to check only one of several boxes. When another box is checked, the previous box is automatically unchecked. Such a group of boxes is often called a radio button group because the buttons work like the station selector buttons on a radio. When you push in one button, the previously depressed button pops out. a typical example. We allow the user to select a font size from among the choices —Small, Medium, Large, and Extra large—but, of course, we will allow the user to select only one size at a time.
A radio button group
Implementing radio button groups is easy in Swing. You construct one object of type Button Group for every group of buttons. Then, you add objects of type JRadio Button to the button group. The button group object is responsible for turning off the previously set button when a new button is clicked.
The second argument of the constructor is true for the button that should be checked initially and false for all others. Note that the button group controls only the behavior of the buttons; if you want to group the buttons for layout purposes, you also need to add them to a container such as a JPanel.
If you look again at Figures below, you will note that the appearance of the radio buttons is different from that of checkboxes. Check boxes are square and contain a check mark when selected. Radio buttons are round and contain a dot when selected. The event notification mechanism for radio buttons is the same as for any other buttons.
When the user checks a radio button, the radio button generates an action event. In our example program, we define an action listener that sets the font size to a particular value:
Compare this listener setup with that of the checkbox example. Each radio button gets a different listener object. Each listener object knows exactly what it needs to do—set the font size to a particular value. In the case of the checkboxes, we used a different approach. Both checkboxes have the same action listener. It called a method that looked at the current state of both checkboxes.
Could we follow the same approach here? We could have a single listener that computes the size as follows:
However, we prefer to use separate action listener objects because they tie the size values more closely to the buttons.
If you have multiple groups of radio buttons in a window, you will want to visually indicate which buttons are grouped. Swing provides a set of useful borders for this purpose. You can apply a border to any component that extends JComponent. The most common usage is to place a border around a panel and fill that panel with other user interface elements such as radio buttons.
You can choose from quite a few borders, but you follow the same steps for all of them.
For example, here is how you add an etched border with a title to a panel:
Run the program in Listing below to get an idea what the various borders look like. The various borders have different options for setting border widths and colors. See the API notes for details. True border enthusiasts will appreciate that there is also a SoftBevelBorder class for beveled borders with softened corners and that a LineBorder can have rounded corners as well. You can construct these borders only by using one of the class constructors—there is no BorderFactory method for them.
Testing border types
If you have more than a handful of alternatives, radio buttons are not a good choice because they take up too much screen space. Instead, you can use a combo box. When the user clicks on the component, a list of choices drops down, and the user can then select one of them.
A combo box
If the drop-down list box is set to be editable, then you can edit the current selection as if it were a text field. For that reason, this component is called a combo box—it combines the flexibility of a text field with a set of predefined choices. The JComboBox class provides a combo box component.
You call the setEditable method to make the combo box editable. Note that editing affects only the current item. It does not change the content of the list.
You can obtain the current selection or edited text by calling the getSelectedItem method.
In the example program, the user can choose a font style from a list of styles (Serif, Sans- Serif, Monospaced, etc.). The user can also type in another font.
You add the choice items with the addItem method. In our program, addItem is called only in the constructor, but you can call it any time.
This method adds the string at the end of the list. You can add new items anywhere in the list with the insert ItemAt method:
You can add items of any type—the combo box invokes each item’s toString method to display it. If you need to remove items at runtime, you use the removeItem or remove ItemAt method, depending on whether you supply the item to be removed or its position.The removeAllItems method removes all items at once.
When the user selects an item from a combo box, the combo box generates an actionevent. To find out which item was selected, call getSource on the event parameter to get areference to the combo box that sent the event. Then call the getSelectedItem method toretrieve the currently selected item. You need to cast the returned value to the appropriatetype, usually String.
Combo boxes let users choose from a discrete set of values. Sliders offer a choice from a continuum of values, for example, any number between 1 and 100.
The most common way of constructing a slider is as follows:
If you omit the minimum, maximum, and initial values, they are initialized with 0, 100, and 50, respectively.
Or if you want the slider to be vertical, then use the following constructor call:
These constructors create a plain slider, such as the top slider. You will see presently how to add decorations to a slider.
As the user slides the slider bar, the value of the slider moves between the minimum and the maximum values. When the value changes, a ChangeEvent is sent to all change listeners.
To be notified of the change, you call the addChangeListener method and install an object that implements the ChangeListener interface. That interface has a single method, stateChanged. In that method, you should retrieve the slider value:
You can embellish the slider by showing ticks. For example, in the sample program, the second slider uses the following settings:
The slider is decorated with large tick marks every 20 units and small tick marks every 5 units. The units refer to slider values, not pixels. These instructions only set the units for the tick marks. To actually have the tick marks appear, you also call
The major and minor tick marks are independent. For example, you can set major tick marks every 20 units and minor tick marks every 7 units, but you’ll get a very messy scale.
You can force the slider to snap to ticks. Whenever the user has finished dragging a slider in snap mode, it is immediately moved to the closest tick. You activate this mode with the call
You can ask for tick mark labels for the major tick marks by calling
For example, with a slider ranging from 0 to 100 and major tick spacing of 20, the ticks are labeled 0, 20, 40, 60, 80, and 100.
You can also supply other tick marks, such as strings or icons. The process is a bit convoluted. You need to fill a hash table with keys of type Integer and values of type Component. (Auto boxing makes this simple in Java SE 5.0 and beyond.) You then call the set Label Table method. The components are placed under the tick marks.
Usually, you use JLabel objects. Here is how you can label ticks as A, B, C, D, E, and F:
Hashtable<Integer, Component> labelTable = new Hashtable<Integer, Component>();
Listing below also shows a slider with icons as tick labels. The fourth slider in has no track. To suppress the “track” in which the slider moves, call
The fifth slider has its direction reversed by a call to
The example program shows all these visual effects with a collection of sliders. Each slider has a change event listener installed that places the current slider value into the text field at the bottom of the frame.
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.