User Interface Components
1. JButtons and JLabel
1.1 Button constructors
We have learnt how to create a button with text by something like JButton("Button1"). Actually there are four JButton constructors with which you can create buttons. They are
JButton(); // create a default button with no text and icon
JButton(String); //create a button with text
JButton(Icon); //create an image button with an image Icon
JButton(String, Icon); //create a button with image and text
JButton(String); //create a button with text
JButton(Icon); //create an image button with an image Icon
JButton(String, Icon); //create a button with image and text
An image icon should be created from ImageIcon class with an image file. For example,
ImageIcon myphoto = new ImageIcon("gaophoto.jpg");
Then you set the icon on a button by
JButton myBtn = new JButton("Junbin Gao", myphoto);
It is pretty simple to create a button.
1.2 Appearance of buttons
After a button is created, you set the button in a special appearance. For example, you can set another icon for the button by usingsetPressedIcon method so that when the user presses the button, the button icon will change to the set one. Similarly you can set a rollover icon by using the setRolloverIcon method.
Read and test the program in Listing 17.1.
Read and test the program in Listing 17.1.
By default the text and icon are centered on the entire button (if the button is large enough). With the button'ssetHorizontalAlignment and setVerticalAlignment methods, you can specify the alignment of text and icon against the button area.
When you have both text and icon on a button, you can use the methods setHorizontalTextPosition andsetVerticalTextPosition to specify the position of text relative to the icon on the button.
The usage of these methods are plain. Program in Listing 17.2 is a good example.
1.3 JLabel constructors
Labels are components that hold text. They have no decorations. They are normally used to identify components. They do not react to user input.
There are four constructors
JLabel(String); // create a text Label
JLabel(Icon); //create a icon Lable
JLabel(String, align); //create an aligned text label
JLabel(String, Icon, align); //create a label with icon and text and
aligned
JLabel(Icon); //create a icon Lable
JLabel(String, align); //create an aligned text label
JLabel(String, Icon, align); //create a label with icon and text and
aligned
where align is an integer constant of JLabel.RIGHT, JLabel.CENTER, JLabel.LEFT
2. Text input
In GUI program, the user input are input into the program through two kinds of components: JTextField and JTextArea.
A text field can accept only one line of text, while a text area can accept multiple lines of text.
Both classes are extended from a class called JTextComponent.
2.1 Creating a JTextField
You can use one of four constructors to create a text field and add it into a panel or other container.
JTextField(); // the default constructor
JTextField(int); // create a text field with a specified number of columns
JTextField(String); //create a text field holding the specified string
JTextField(String, int);//create a text field holding the string and
//with a specified number of columns
By default, once a text field is created, the user can input new text into the field. However you can dismiss this capability by usingsetEditable(false).
JTextField(int); // create a text field with a specified number of columns
JTextField(String); //create a text field holding the specified string
JTextField(String, int);//create a text field holding the string and
//with a specified number of columns
By default, once a text field is created, the user can input new text into the field. However you can dismiss this capability by usingsetEditable(false).
Also you can align the text in the area by the setHorizontalAlignment method.
2.2 Creating a JTextAreas
The simplest way to create a text area is to use the default constructor
JTextArea myarea = new JTextArea();
Also you can use the other three constructors
JTextArea(int rows, int cols);
JTextArea(String text); //put initial text in the area
JTextArea(String text, int rows, int cols); //put initial text
JTextArea(String text); //put initial text in the area
JTextArea(String text, int rows, int cols); //put initial text
The class provides a lot of methods to control the appearance of the textarea objects. For example, you can add additional text to the area with the append method; you can get the actual number of lines contained in the text area by the getLineCount method.
2.3 Example: Input from JTextField and Display in JTextAreas
We are going to develop a small demonstration application. The program's main frame consists of one JTextField for the user input and one JTextArea to display the user input. Once the user press the "return" key, the input will be immediately added into the display area.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.*;
import java.awt.event.*;
public class TestTextFieldArea {
public static void main( String[] argv ) {
JFrame myframe = new TextFrame();
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
public static void main( String[] argv ) {
JFrame myframe = new TextFrame();
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.setVisible(true);
}
}
class TextFrame extends JFrame
{
public TextFrame(){
TextPanel p = new TextPanel();
add(p);
setTitle("Text Field and Area");
setSize(400, 400);
setLocationRelativeTo(null);
}
}
{
public TextFrame(){
TextPanel p = new TextPanel();
add(p);
setTitle("Text Field and Area");
setSize(400, 400);
setLocationRelativeTo(null);
}
}
class TextPanel extends JPanel
{
private JTextField text = new JTextField(20);
private JTextArea area = new JTextArea("", 18, 30);
public TextPanel()
{
JLabel label1 = new JLabel("Please input:");
JLabel label2 = new JLabel("What you have input:");
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setEditable(false);
JPanel small = new JPanel();
small.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
small.add(label1);
small.add(text);
JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 1, 5, 5));
top.add(small);
top.add(label2);
JScrollPane areaScroll = new JScrollPane(area);
//use a scroll pane to hold text area?
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eve){
area.append(" "+text.getText());
text.setText("");
}
});
setLayout(new BorderLayout(5,5));
add(top, BorderLayout.NORTH);
add(areaScroll, BorderLayout.CENTER);
}
}
{
private JTextField text = new JTextField(20);
private JTextArea area = new JTextArea("", 18, 30);
public TextPanel()
{
JLabel label1 = new JLabel("Please input:");
JLabel label2 = new JLabel("What you have input:");
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setEditable(false);
JPanel small = new JPanel();
small.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
small.add(label1);
small.add(text);
JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 1, 5, 5));
top.add(small);
top.add(label2);
JScrollPane areaScroll = new JScrollPane(area);
//use a scroll pane to hold text area?
text.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent eve){
area.append(" "+text.getText());
text.setText("");
}
});
setLayout(new BorderLayout(5,5));
add(top, BorderLayout.NORTH);
add(areaScroll, BorderLayout.CENTER);
}
}
3. JCheckBox and JRadioButton
Both classes extend the JToggleButton which is from the AbstractButton. They are used to enable the user to toggle a choice yes or no.
3.1 Creating and Using JCheckBox
Read the demo program in Listing 17.3.
The constructors of JCheckBox are very similar to the constructors of JLabel. A checkbox has a label (text or/and icon) next to the tickable square. When the checkbox is on (yes), there is a small tick in the square.
Usually we shall organize a number of check boxes as a group for purposes. This is done by grouping them with a JPanel. Find out which lines in Listing 17.3 are doing this.
Please note that when a check box is clicked, it triggers an ItemEvent and THEN an ActionEvent. You can use the isSelected method to check the status of the check box (yes/no or on/off).
3.2 Creating Radio Buttons
Radio buttons enable the user to choose a single item from a group of choices. Radio buttons resembles check boxes in appearance.
If you can create a check box, then you can certainly create a radio button. Or please refer to page 605 (8E) of the text book for the description of its constructors.
The radio buttons created by JRadioButton constructors are independent of each other. To enable us to get an exclusive choose in a number of radio buttons, we need to group radio buttons. This can be done by adding radio buttons into an instance of ButtonGroupclass.
ButtonGroup is not a component, so it can not be added into a container. ButtonGroup just logically group radio buttons together to create a mutually exclusive group. You still need a panel to physically/visually group (arrange) them on a window.
Just like check boxes, a radio button triggers an ItemEvent and THEN an ActionEvent. You can use corresponding listeners to capture them.
Please try the program in Listing 17.4.
4. Combo Boxes and Lists
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 or a list.
4.1 Creating Combo Boxes
A combo box, also known a choice list or drop-down list, contains a list of items from which the user can choose.
The best way to create a combo box is to create an empty one with the default constructor, then use the addItem method to add items into the combo box. The following code segment demonstrate this way,
myCombo = new JCombo();
myCombo.addItem("Serif");
myCombo.addItem("SansSerif");
myCombo.addItem("Monospaced");
myCombo.addItem("RomeTimes");
myCombo.addItem("Serif");
myCombo.addItem("SansSerif");
myCombo.addItem("Monospaced");
myCombo.addItem("RomeTimes");
You can add items of any type, but the combo box invokes each item's toString method to display it in the box.
You can also remove any item with the removeItem or removeItemAt methods.
Study more methods in Figure 17.21 or Java document.
4.2 Events from Combo Boxes
When the user select an item from a JComboBox, it can generate ActionEvent and ItemEvent. To find out which item was selected, you call the getSelectedItem method to retrieve the currently selected item. If the user change the selected item, then the combo box triggers ItemEvent twice, one for deselecting the previously selected item and one for the new selected item.
ItemEvent should be listened by the ItemListener and processed by the itemStateChanged handler in the ItemListener.
4.3 Creating JLists
A list is a component that basically performs the same functuion as a combo box but it is not a combo box, you create an empty list with the default constructor then add the items into the list with the
Usually we create an array of items (or a vector of items) and then create the JList with the array (or the vector). The following is an example
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
You can make an item selected in the list by
dataList.setSelectedIndex(1); // select "two"
You can get the seleted item index by the getSelectedIndex() method or the selected item by the getSelectedValue method.
You can set the number of visible items by the setVisibleRowCount(int) method.
4.4 The Events from JList
JList triggers ListSelectionEvent and a ListSelectionListener should be registered with the JList to listen to the event. The listener must implement the valueChanged method to process the event.
Please study the examples in Section 17.8 and 17.9.
5. Sliders and Scroll Bars
5.1 Creating Sliders
The 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
JSlider myslider = new JSlider(min, max, initialValue);
The default values for them are 0, 100 and 50, respectively.
If you need a vertical slider, you can create it in the following way
JSlider myslider = new JSlider(JSlider.VERTICAL, min, max, initialValue);
As the user sldies 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 the ChangeListener registered with the slider. The ChangerListener must implement thestateChanged method to process the value change on the slider.
For more details please refer to Section 17.11 on page 623 (8E) of the text book
5.2 Creating Scrolling Bars
JScrollBar is a component that enables the user to select from a range of values, see Figure 17.26 on page 620 (8E) of the text book.
On the scroll bar, the user can drag the bubble on the two directions to increase or decrease values, or click in the scroll bar's unit/block-increment/decrement areas.
To create a scroll bar, use one of
JScrollBar mysco = new JScrollBar(JSlider.HORIZONTAL);
JScrollBar mysco = new JScrollBar(JSlider.VERTICAL);
JScrollBar mysco = new JScrollBar(JSlider.VERTICAL, value, extent, min, max);
JScrollBar mysco = new JScrollBar(JSlider.VERTICAL);
JScrollBar mysco = new JScrollBar(JSlider.VERTICAL, value, extent, min, max);
When the user changes a scroll bar's value, the scroll bar triggers an AdjustmentEvent which is passed to the registeredAdjustmentListener. The AdjustmentListener?s adjustmentValueChanged method should be implemented to process the changes.
No comments:
Post a Comment