Advanced GUI Applications Part I
- Contents
- The Swing and AWT Class Hierarchy
- Read Only Text Fields
- Lists
- Combo Boxes
- Displaying Images in Labels and Buttons
- Mnemonics
- Tool Tips
- File Choosers
- Color Choosers
- Menus
- Text Areas
- Fonts
- Sliders
- Look and Feel
The Swing and AWT Class Hierarchy

Read Only Text Fields
By default a text field is editable.
The
JTextFieldcomponent has a method namedsetEditable:The
setEditablemethod must be passedfalseto make the field read-only.
setEditable(boolean editable)
Lists
A list is a component that displays a list of items and allows the user to select items from the list.
The
JListcomponent is used for creating lists.When an instance of the
JListclass is created, an array of objects is passed to the constructor.JList (Object[] array)
The
JListcomponent uses the array to create the list of items.String[] name = { "Jade", "Bob", "Katie" }; JList nameList = new JList(names);List Selection Modes
The
JListcomponent can operate in any of the following selection modes:Single Selection Mode: Only one item can be selected at a time.

Single Interval Selection Mode: Multiple items can be selected, but they must be in a single interval. An interval is a set of contiguous items.

Multiple Interval Selection Mode: In this mode, multiple items may be selected with no restrictions.

The “Multiple Interval Selection Mode” is the default selection mode.
We change a
JListcomponent’s selection mode with thesetSelectionModemethod.The method accepts an
intargument that should be one of the following values:nameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); nameList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); nameList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
List Events
When an item in a
JListobject is selected it generates a list selection event.The event is handled by a class that meets the following requirements.
It must implement the
ListSelectionListenerinterface.It must have a method named
valueChanged. This method must take an argument of theListSelectionEventtype.
Use the
addListSelectionListenermethod of theJListclass to register the instance of the list selection listener class with the list object.When the
JListcomponent generates an event:It automatically executes the
valueChangedmethod of the list selection listener object.It passes the event object as an argument.
Retrieving Selected Items
You may use
getSelectedValueorgetSelectedIndexto determine which item in a list is currently selected.getSelectedValuereturns anObjectreference.String selectedName; selectedName = (String)nameList.getSelectedValue();
In this example, the return value must be down casted to
Stringin order to store it in theselectedNamevariable.If no item in the list is selected, the method returns
null.The
getSelectedIndexmethod returns the index of the selected item, or -1 if no item is selected.Internally, the items that are stored in a list are numbered, similar to an array. Each item’s number is called its index. The first item has the index of 0.
We can use the index of the selected item to retrieve the item from an array.
String[] name = { "Jade", "Bob", "Katie" }; int index = nameList.getSelectedIndex(); if (index != -1) selectedName = name[index];
Book example
The
setBoradermethod can be used to draw a border around aJList.list.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
By default, a list component is large enough to display all of the items it contains. Most GUI applications display a scroll bar on list components that contain a large number of items.
List components do not automatically display a scroll bar. To display a scroll bar on a list component:
Set the number of visible rows for the list component.
Create a
JScrollPaneobject and add the list component to it.Add the
JScrollPaneobject to any other container, such as a panel.
By default, a
JListcomponent added to aJScrollPaneonly displays a scroll bar only if there are more items in the list than there are visible rows.Book example:
We can replace items in an existing
JListcomponent.void setListData(Object[] data)
This replaces any items that are currently displayed in the component. This can be used to add items to an empty list.
When a
SINGLE_INTERVAL_SELECTIONorMULTIPLE_INTERVAL_MODEis used,The
getSelectedValuemethod returns the first item in from the selection.The
getSelectedIndexmethod returns the index of the first item from the selection.We use the
getSelectedValuesmethod to get the entire list of selected itemsWe use the
getSelectedIndicesmethod to get the entire list of the selected indices.
Book example
Example code:
import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; public MainWindow() { super("JText Field and JList Demo"); // Set the size for this window, and use a flow layout manager to // automatically control the bounds of the components; automatically // dispose resources for this instance when it is closed by the user. this.setSize(700, 300); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // Create a list, add it to a scroll pane, which is added to this // instance. final String[] listItems = { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Ascension Island", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros" }; final JList list = new JList(); list.setListData(listItems); list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list.setVisibleRowCount(10); final JScrollPane scrollPane = new JScrollPane(list); this.add(scrollPane); // Create a text field and add it to this instance. final JTextField field = new JTextField(50); field.setEditable(false); this.add(field); // Display selected items in the text field. list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(final ListSelectionEvent evt) { final int[] selectedIndices = list.getSelectedIndices(); final StringBuilder builder = new StringBuilder(); for (final int index : selectedIndices) builder.append(" " + listItems[index]); field.setText(builder.toString()); } }); } }
Combo Boxes
A combo box presents a drop-down list of items that the user may select from.
The
JComboBoxclass is used to create a combo box.
String[] names = { "Jade", "Bob", "Katie" };
JComboBox nameBox = new JComboBox(names);
A button is displayed next to the currently selected item.
The first item in the list is automatically selected when the combo box is displayed.
When the user clicks on the button, the drop-down list appears, and the user may select another item.
Combo Box Events
When an item in a
JComboBoxobject is selected, it generates an action event.Action events are handled with an action event listener class, which must have an
actionPerformedmethod.When the user selects an item in a combo box, the combo box executes its action event listener’s
actionPerformedmethod, passing anActionEventobject as an argument.
Retrieving Selected Items
There are two methods in the
JComboBoxclass that can be used to determine which item in a list is currently selected.The
getSelectedItemmethod returns a reference to the item that is currently selected.String selectedName = (String)nameBox.getSelectedItem();
The
getSelectedIndexmethod returns the index of the selected item.int index = nameBox.getSelectedIndex(); String selectedName = names[index];
Book example:
There are two types of combo boxes:
uneditable: allows the user to select items only from its list.
editable: combines a text field and a list
- It allows the selection of items from the list.
- It also allows the user to type input into the text field.
The
setEditablemethod sets the edit mode for the component.nameBox.setEditable(true);
Example code:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public final class Program implements Runnable {
public static void main(final String[] args) {
SwingUtilities.invokeLater(new Program());
}
@Override
public void run() {
final MainWindow window = new MainWindow();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
final class MainWindow extends JFrame {
private static final long serialVersionUID = -726678164482368106L;
public MainWindow() {
super("JComboBox Demo");
// Set the size for this window, and use a flow layout manager to
// automatically control the bounds of the components; automatically
// dispose resources for this instance when it is closed by the user.
this.setSize(700, 300);
this.setLayout(new FlowLayout());
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
// Create a combo box and add it to this instance.
final String[] items = { "Afghanistan", "Albania", "Algeria",
"American Samoa", "Andorra", "Angola", "Anguilla",
"Antarctica", "Antigua and Barbuda", "Argentina", "Armenia",
"Aruba", "Ascension Island", "Australia", "Austria",
"Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados",
"Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan",
"Bolivia", "Bosnia and Herzegovina", "Botswana",
"Bouvet Island", "Brazil", "British Indian Ocean Territory",
"Brunei Darussalam", "Bulgaria", "Burkina Faso", "Burundi",
"Cambodia", "Cameroon", "Canada", "Cape Verde",
"Cayman Islands", "Central African Republic", "Chad", "Chile",
"China", "Christmas Island", "Cocos (Keeling) Islands",
"Colombia", "Comoros" };
final JComboBox comboBox = new JComboBox(items);
comboBox.setEditable(true);
this.add(comboBox);
// Create a text field and add it to this instance.
final JTextField field = new JTextField(50);
field.setEditable(false);
this.add(field);
// Display selected or entered item in the text field.
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent evt) {
final String selected = (String) comboBox.getSelectedItem();
field.setText(selected);
}
});
}
} Displaying Images in Labels and Buttons
Labels can display text, an image, or both.
To display an image, create an instance of the
ImageIconclass, which reads the image file.The constructor accepts the path of an image file.
The supported file types are JPEG, GIF, and PNG.
ImageIcon image = new ImageIcon("my-pic.png"); ImageIcon image = new ImageIcon("C:\chaper12\images\my-pic.png");The image is assigned by passing the
ImageIconobject as an argument to theJLabelconstructor.JLabel(Icon image)
The argument passed can be an
ImageIconobject or any object that implements theIconinterface.Creating a button with an image is similar to that of creating a label with an image.
ImageIcon image = new ImageIcon("my-pic.png"); JButton button = new JButton(image); button.setIcon(image);Book example:
Example code:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; boolean isOne = true; public MainWindow() { super("Label with Image Demo"); // Set the size for this window, and use a flow layout manager to // automatically control the bounds of the components; automatically // dispose resources for this instance when it is closed by the user. this.setSize(200, 200); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // Create a label with a image and add it to this instance. final ImageIcon image = new ImageIcon("1.png"); final JLabel label = new JLabel(image); this.add(label); // Create a button and add it to this instance. final JButton button = new JButton("Toggle"); this.add(button); // Toggle the image when the button is clicked. button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { final ImageIcon icon; if (MainWindow.this.isOne) icon = new ImageIcon("2.png"); else icon = new ImageIcon("1.png"); label.setIcon(icon); MainWindow.this.isOne = !MainWindow.this.isOne; } }); } }
Mnemonics
A mnemonic is a key that you press to quickly access a component. In Windows, this is sometimes used in combination with the Alt key.
A mnemonic key is assigned to a component through the component’s
setMnemonicmethod.The argument passed to the method is an integer code that represents the key you wish to assign.
The key codes are predefined constants in the
KeyEventclass (java.awt.eventpackage).These constants take the form:
// To assign the X key as a mnemonic. // The letter VK in the sonstants stand for "virtual key" JButton exitButton = new JButton("Exit"); exitButton.setMnemonic(KeyEvent.VK_X)If the letter is in the component’s text, the first occurrence of that letter will appear underlined.
If the letter does not appear in the component’s text, then no letter will appear underlined.
Example code:
import java.awt.FlowLayout; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JRadioButton; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; public MainWindow() { super("Mnemonics Demo"); // Set the size for this window, and use a flow layout manager to // automatically control the bounds of the components; automatically // dispose resources for this instance when it is closed by the user. this.setSize(250, 100); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // Create radio buttons with mnemonic keys and add them to this instance. final JRadioButton button1 = new JRadioButton("Breakfast"); button1.setMnemonic(KeyEvent.VK_B); this.add(button1); final JRadioButton button2 = new JRadioButton("Lunch"); button2.setMnemonic(KeyEvent.VK_L); this.add(button2); final JRadioButton button3 = new JRadioButton("Dinner"); button3.setMnemonic(KeyEvent.VK_D); this.add(button3); // Create a group to enforce mutual exclusion. final ButtonGroup group = new ButtonGroup(); group.add(button1); group.add(button2); group.add(button3); } }
Tool Tips
A tool tip is text that is displayed in a small box when the mouse hovers over a component.
The box usually gives a short description of what the component does.
Most GUI applications use tool tips as concise help.
To assign a tool tip to a component the
setToolTipTextmethod is used.Example code:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; public MainWindow() { super("Mnemonics Demo"); // Set the size for this window, and use a flow layout manager to // automatically control the bounds of the components; automatically // dispose resources for this instance when it is closed by the user. this.setSize(250, 100); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); // Create button with a hot key and some tool tip text and add this // button to this instance. final JButton button = new JButton("Exit"); button.setMnemonic(KeyEvent.VK_X); button.setToolTipText("Click here to exit."); this.add(button); // Exit the appliction when the button is clicked. button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { MainWindow.this.dispose(); } }); } }
File Choosers
A file choose is a specialized dialog box that allows the user to browse for a file and select it.


The
JFileChooserclass is used to display a file choose dialog box.Two of the constructors have the form:
JFileChooser(); JFileChooser(String path);
The first constructor takes no arguments and uses the default directory as the starting point for all of its dialog boxes.
The second constructor takes a
Stringargument containing a valid path. This path will be the starting point of the objects’s dialog box.A
JFileChooseobject can display two types of predefined dialog boxes:Open File dialog box: lets the user browse for an existing file to open.
Save File dialog box: lets the user browse to a location to save a file.
The
showOpenDialogmethod is used to display an Open File dialog box.int showOpenDialog(Component parent)
The
showSaveDialogmethod is used to display a Save File dialog box.int showSaveDialog(Component parent)
For both of these two methods:
The argument can be
nullor a reference to a component.If
nullis passed, the dialog box is centered in the screen.If a reference to a component is passed the dialog box is centered over the component.
Both methods return an integer that indicates the action taken by the user to close the dialog box. We can compare the return value to one of the following constants:
JFileChooser.CANCEL_OPTION: indicates that the user clicked the Cancel button.JFileChooser.APPROVE_OPTION: indicates that the user clicked the OK button.JFileChooser.ERROR_OPTION: indicates that an error occurred, or the user clicked on the standard close button on the window to dismiss it.
If the user selected a file, the
getSelectedFilemethod can be used to determine the file that was selected.The
getSelectedFilemethod returns aFileobject that contains data about the selected file.The
Fileobject’sgetPathmethod can be used to get the path and the file name as aString
Example code:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; public MainWindow() { super("File Chooser Demo"); this.setSize(250, 100); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); final JButton buttonOne = new JButton("Open"); final JButton buttonTwo = new JButton("Save"); this.add(buttonOne); this.add(buttonTwo); buttonOne.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MainWindow.this.openFile(); } }); buttonTwo.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MainWindow.this.saveFile(); } }); } void openFile() { final JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { final File selected = fileChooser.getSelectedFile(); try { final Scanner scanner = new Scanner(selected); while (scanner.hasNextLine()) System.out.println(scanner.nextLine()); } catch (final FileNotFoundException e) { System.err.println("File not found."); } } } void saveFile() { final JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { final File selected = fileChooser.getSelectedFile(); try { final PrintStream printer = new PrintStream(selected); printer.println("this is the first line"); printer.println("this is the second line"); } catch (final FileNotFoundException e) { System.err.println("File not found."); } } } }
Color Choosers
A color chooser is a specialized dialog box that allows the user to select a color from a predefined palette of colors.


By clicking the HSB tab, it is possible to select a color by specifying its hue, saturation, and brightness.
By clicking the RGB tab, it is possible to select a color by specifying its red, green, and blue components.
The
JColorChooserclass has a static method namedshowDialog, with the following general format:Color showDialog(Component parent, String title, Color initial)
If the first argument is
null, the dialog box is normally centered in the screen.If it is a reference to a component the dialog box is centered over the component.
The second argument is the dialog title
The third argument indicates the color that appears initially selected in the dialog box.
This method returns the color selected by the user.
Example code:
import java.awt.Color; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; public MainWindow() { super("Color Chooser Demo"); this.setSize(250, 100); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); final JButton buttonOne = new JButton("Color"); this.add(buttonOne); buttonOne.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { MainWindow.this.chooseColor(); } }); } void chooseColor() { final Color selected = JColorChooser.showDialog( this, "Color Chooser", Color.BLUE); System.out.println("selected color: " + selected); } }
Menus
A menu system is a collection of commands organized in one or more drop-down menus.

A menu system commonly consists of:
Menu Bar lists the names of one or more menus Menu a drop-down list of menu items Menu Item can be selected by the user Check Box Menu Item appears with a small box beside it Radio Button Menu Item may be selected or deselected Submenu a menu within a menu Separator Bar a horizontal bar used to separate groups of items on a menu A menu system is constructed with the following classes:
JMenuBarJMenuJMenuItemJCheckBoxMenuItem
Example code:
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.SwingUtilities; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -726678164482368106L; public MainWindow() { super("Menu Demo"); this.setSize(250, 250); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); final JRadioButtonMenuItem itemOne = new JRadioButtonMenuItem("One", true); final JRadioButtonMenuItem itemTwo = new JRadioButtonMenuItem("Two"); final JMenuItem exit = new JMenuItem("Exit"); final JMenu menu = new JMenu("Menu"); menu.add(itemOne); menu.add(itemTwo); menu.addSeparator(); menu.add(exit); final ButtonGroup group = new ButtonGroup(); group.add(itemOne); group.add(itemTwo); final JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); this.setJMenuBar(menuBar); final ImageIcon image = new ImageIcon("1.png"); final JLabel label = new JLabel(image); this.add(label); itemOne.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { final ImageIcon icon = new ImageIcon("1.png"); label.setIcon(icon); } }); itemTwo.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { final ImageIcon icon = new ImageIcon("2.png"); label.setIcon(icon); } }); exit.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { MainWindow.this.dispose(); } }); } }
Text Areas
The
JTextFieldclass is used to create text fields.A text field is a component that allows the user to enter a single line of text.
A text area is like a text field that can accept multiple lines of input.
The
JTextAreaclass is used to create text areas.The general format of the class’s constructor:
JTextArea(Stromg text)
The
JTextAreaclass provides thegetTextandsetTextmethods for getting and setting the text.JTextArea area; : String userText = area.getText(); area.setText("new text");JTextAreacomponents do not automatically display scroll bars.To display scroll bars a
JTextAreamust be added to aJScrollPane.JTextArea textArea = new JTextArea("initial text"); JScrollPane scrollPane = new JScrollPane(textArea);The
JScrollPaneobject displays both vertical and horizontal scroll bars on a text area.By default, the scroll bars are not displayed until they are needed.
This behavior can be altered with:
scrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); scrollPane.setHorizontalScrollBarPolicy( ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);The following constants are available to alter the behavior:
setHorizontalScrollBarPolicyJScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED. JScrollPane.HORIZONTAL_SCROLLBAR_NEVER JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
setHorizontalScrollBarPolicyJScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED JScrollPane.VERTICAL_SCROLLBAR_NEVER JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
Be default,
JTextAreacomponents do not perform line wrapping.To enable line wrapping:
textArea.setLineWrap(true);
There are two different styles of line wrapping.
word wrapping: the line breaks always occur between words.
textArea.setWrapStyleWord(true);
character wrapping: the lines are broken between characters. This is the default mode.
Fonts
Text components display according to their font characteristics:
font: the name of the typeface.
style: plain, bold, italic.
size: size of the text in points.
A component’s
setFontmethod will change the appearance of the text in the component:setFont(Font font)
A
Fontconstructor takes three parameters:Font(String fontName, int style, int size)
Java guarantees that you will have the following fonts:
DialogDialogInputMonospacedSansSerifSerif
There are three font styles:
Font.PLAINFont.BOLDFont.ITALIC
Example:
label.setFont(new Font("Serif", Font.BOLD, 24); label.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 24);
Sliders
A slider is a component that allows the user to graphically adjust a number within a range.


Sliders are created from the
JSliderclass.They display an image of a “slider knob” that can be dragged along a track.
A slider is designed to represent a range of numeric values.
As the user moves the knob along the track, the numeric value is adjusted accordingly.
Between the minimum and maximum values, major tick marks are displayed with a label indicating the value at that tick mark.
Between the major tick marks are minor tick marks.
The
JSliderconstructor has the general format:JSlider(int orientation, int minValue, int maxValue, int initialValue)
for orientation, one of these constants should be used:
JSlider.HORIZONTAL JSlider.VERTICAL
The major and minor tick mark spacing can be set with:
setMajorTickSpacing setMinorTickSpacing
The tick marks can be displayed by calling:
mySlider.setPaintTicks(true);
The numeric labels can be displayed by calling
mySlider.setPaintLabels(true);
When the knob’s position is moved, the slider component generates a change event.
A change listener class is created to handle the change event.
A change listener class must meet the following requirements:
It must implement the
ChangeListenerinterface.It must have a method named
stateChanged.This method must take an argument of the
ChangeEventtype.
To retrieve the current value stored in a
JSlider, we use thegetValuemethod.Example code:
import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JSlider; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = -3058699892319739488L; public MainWindow() { super("Slider Demo"); this.setSize(200, 250); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); final JSlider slider = new JSlider(SwingConstants.VERTICAL, 0, 100, 80); slider.setMajorTickSpacing(10); slider.setMinorTickSpacing(5); slider.setPaintLabels(true); slider.setPaintTicks(true); this.add(slider); final JLabel label = new JLabel("Grade look up"); this.add(label); slider.addChangeListener(new ChangeListener() { @Override public void stateChanged(final ChangeEvent evt) { final int grade = slider.getValue(); final char letterGrade = convertToLetterGrade(grade); label.setText("Grade: " + grade + " -> " + letterGrade); } }); } static char convertToLetterGrade(final int grade) { if (grade < 60) return 'F'; if (grade < 70) return 'D'; if (grade < 80) return 'C'; if (grade < 90) return 'B'; return 'A'; } }
Look and Feel
The appearance of a particular system’s GUI is known as its look and feel.




Java allows you to select the look and feel of a GUI application.
On most systems, Java’s default look and feel is called Metal.
Java also provides Motif and Windows look and feel classes.
Motif is similar to an ancient UNIX look and feel
Windows is the look and feel of the Windows (95) operating system.
To change an application’s look and fell, we call the
UIManagerclass’s staticsetLookAndFeelmethod.Java has a class for each look and feel.
The
setLookAndFeelmethod takes the fully qualified class name for the desired look and feel as its argument.The class name must be passed as a String.
Example look and feels
javax.swing.plaf.metal.MetalLookAndFeel com.sun.java.swing.plaf.gtk.GTKLookAndFeel com.sun.java.swing.plaf.motif.MotifLookAndFeel com.sun.java.swing.plaf.windows.WindowsLookAndFeel
Look and feel is generally assigned when the application starts and before any components have been created.
To determine the recommended look and feel for the application, the following method can be used.
String name = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(name);
Example code:
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.UIManager; public final class Program implements Runnable { public static void main(final String[] args) { SwingUtilities.invokeLater(new Program()); } @Override public void run() { final MainWindow window = new MainWindow(); window.setLocationRelativeTo(null); window.setVisible(true); } } final class MainWindow extends JFrame { private static final long serialVersionUID = 6933840657337621389L; int index = 0; final String[] lookAndFeels = { "javax.swing.plaf.metal.MetalLookAndFeel", "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", "com.sun.java.swing.plaf.motif.MotifLookAndFeel" }; public MainWindow() { super("Look and Feel Demo"); this.setSize(400, 100); this.setLayout(new FlowLayout()); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); final JButton button = new JButton("Button"); final JLabel label = new JLabel("Default Look and Feel"); this.add(button); this.add(label); button.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent evt) { final MainWindow owner = MainWindow.this; try { final String lookAndFeel = owner.lookAndFeels[owner.index++ % 3]; UIManager.setLookAndFeel(lookAndFeel); SwingUtilities.updateComponentTreeUI(owner); label.setText(lookAndFeel); } catch (final Exception e) { e.printStackTrace(); } } }); } }