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
JTextField
component has a method namedsetEditable
:The
setEditable
method must be passedfalse
to 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
JList
component is used for creating lists.When an instance of the
JList
class is created, an array of objects is passed to the constructor.JList (Object[] array)
The
JList
component uses the array to create the list of items.String[] name = { "Jade", "Bob", "Katie" }; JList nameList = new JList(names);
List Selection Modes
The
JList
component 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
JList
component’s selection mode with thesetSelectionMode
method.The method accepts an
int
argument 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
JList
object is selected it generates a list selection event.The event is handled by a class that meets the following requirements.
It must implement the
ListSelectionListener
interface.It must have a method named
valueChanged
. This method must take an argument of theListSelectionEvent
type.
Use the
addListSelectionListener
method of theJList
class to register the instance of the list selection listener class with the list object.When the
JList
component generates an event:It automatically executes the
valueChanged
method of the list selection listener object.It passes the event object as an argument.
Retrieving Selected Items
You may use
getSelectedValue
orgetSelectedIndex
to determine which item in a list is currently selected.getSelectedValue
returns anObject
reference.String selectedName; selectedName = (String)nameList.getSelectedValue();
In this example, the return value must be down casted to
String
in order to store it in theselectedName
variable.If no item in the list is selected, the method returns
null
.The
getSelectedIndex
method 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
setBorader
method 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
JScrollPane
object and add the list component to it.Add the
JScrollPane
object to any other container, such as a panel.
By default, a
JList
component added to aJScrollPane
only 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
JList
component.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_SELECTION
orMULTIPLE_INTERVAL_MODE
is used,The
getSelectedValue
method returns the first item in from the selection.The
getSelectedIndex
method returns the index of the first item from the selection.We use the
getSelectedValues
method to get the entire list of selected itemsWe use the
getSelectedIndices
method 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
JComboBox
class 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
JComboBox
object is selected, it generates an action event.Action events are handled with an action event listener class, which must have an
actionPerformed
method.When the user selects an item in a combo box, the combo box executes its action event listener’s
actionPerformed
method, passing anActionEvent
object as an argument.
Retrieving Selected Items
There are two methods in the
JComboBox
class that can be used to determine which item in a list is currently selected.The
getSelectedItem
method returns a reference to the item that is currently selected.String selectedName = (String)nameBox.getSelectedItem();
The
getSelectedIndex
method 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
setEditable
method 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
ImageIcon
class, 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
ImageIcon
object as an argument to theJLabel
constructor.JLabel(Icon image)
The argument passed can be an
ImageIcon
object or any object that implements theIcon
interface.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
setMnemonic
method.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
KeyEvent
class (java.awt.event
package).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
setToolTipText
method 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
JFileChooser
class 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
String
argument containing a valid path. This path will be the starting point of the objects’s dialog box.A
JFileChoose
object 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
showOpenDialog
method is used to display an Open File dialog box.int showOpenDialog(Component parent)
The
showSaveDialog
method is used to display a Save File dialog box.int showSaveDialog(Component parent)
For both of these two methods:
The argument can be
null
or a reference to a component.If
null
is 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
getSelectedFile
method can be used to determine the file that was selected.The
getSelectedFile
method returns aFile
object that contains data about the selected file.The
File
object’sgetPath
method 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
JColorChooser
class 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:
JMenuBar
JMenu
JMenuItem
JCheckBoxMenuItem
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
JTextField
class 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
JTextArea
class is used to create text areas.The general format of the class’s constructor:
JTextArea(Stromg text)
The
JTextArea
class provides thegetText
andsetText
methods for getting and setting the text.JTextArea area; : String userText = area.getText(); area.setText("new text");
JTextArea
components do not automatically display scroll bars.To display scroll bars a
JTextArea
must be added to aJScrollPane
.JTextArea textArea = new JTextArea("initial text"); JScrollPane scrollPane = new JScrollPane(textArea);
The
JScrollPane
object 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:
setHorizontalScrollBarPolicy
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED. JScrollPane.HORIZONTAL_SCROLLBAR_NEVER JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
setHorizontalScrollBarPolicy
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED JScrollPane.VERTICAL_SCROLLBAR_NEVER JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
Be default,
JTextArea
components 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
setFont
method will change the appearance of the text in the component:setFont(Font font)
A
Font
constructor takes three parameters:Font(String fontName, int style, int size)
Java guarantees that you will have the following fonts:
Dialog
DialogInput
Monospaced
SansSerif
Serif
There are three font styles:
Font.PLAIN
Font.BOLD
Font.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
JSlider
class.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
JSlider
constructor 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
ChangeListener
interface.It must have a method named
stateChanged
.This method must take an argument of the
ChangeEvent
type.
To retrieve the current value stored in a
JSlider
, we use thegetValue
method.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
UIManager
class’s staticsetLookAndFeel
method.Java has a class for each look and feel.
The
setLookAndFeel
method 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(); } } }); } }