JAVAX.
SWING
1. The Swing User Interface
This example creates and shows a frame with a button. To enable the button to respond to
button clicks,.
import [Link].*;
import [Link].*;
public class BasicUI {
public static void main(String[] args) {
JButton button = new JButton("Label");
JFrame frame = new JFrame();
// Add button to the frame
[Link]().add(button, [Link]);
// Set initial size
int frameWidth = 300;
int frameHeight = 300;
[Link](frameWidth, frameHeight);
// Show the frame
[Link](true);
}
}
JFRAME,JWINDOW,JDIALOG
2. Creating a JFrame
A frame is a component container that displays its contents in a top-level window with a
title bar and buttons to resize, iconify, maximize, and close the frame.
Unlike most Swing containers, adding a component to a frame is not done with the
[Link]() method. This is because the frame holds several panes and it is necessary
to specify a particular pane to which to add the component. The pane that holds child
components is called the content pane. This example adds a text area to the content pane
of a frame.
// Create the frame
String title = "Frame Title";
JFrame frame = new JFrame(title);
// Create a component to add to the frame
JComponent comp = new JTextArea();
// Add the component to the frame's content pane;
// by default, the content pane has a border layout
[Link]().add(comp, [Link]);
// Show the frame
int width = 300;
int height = 300;
[Link](width, height);
[Link](true);
3. Exiting an Application When a JFrame Is Closed
By default, when the close button on a frame is clicked, the frame hides itself. This
example shows how to exit the application when the frame is closed:
// Create a frame
JFrame frame = new JFrame();
// Get default close operation
int op = [Link](); // HIDE_ON_CLOSE
// Set to exit on close
[Link](JFrame.EXIT_ON_CLOSE);
4. Disabling the Close Button on a JFrame
By default, when the close button on a frame is clicked, the frame hides itself. This
example shows how to disable the close button:
// Create a frame
JFrame frame = new JFrame();
// Get default close operation
int op = [Link](); // HIDE_ON_CLOSE
// Set to ignore the button
[Link](JFrame.DO_NOTHING_ON_CLOSE);
5. Creating a Borderless Window
JWindow window = new JWindow();
// Add component to the window
[Link]().add(component, [Link]);
// Set initial size
[Link](300, 300);
// Show the window
[Link](true);
6. Showing a Dialog Box
// Modal dialog with OK button
String message = "Line1\nLine2";
[Link](frame, message);
// Modal dialog with yes/no button
int answer = [Link](frame, message);
if (answer == JOptionPane.YES_OPTION) {
// User clicked YES.
} else if (answer == JOptionPane.NO_OPTION) {
// User clicked NO.
}
// Modal dialog with OK/cancel and a text field
String text = [Link](frame, message);
if (text == null) {
// User clicked cancel
}
7. Getting the JFrame of a Component
In order to find the frame that contains a component, it is necessary to walk up the
component's parents until the frame is encountered. [Link]() is a
convenience method that finds the frame.
This example implements an action that finds and hides the frame of the component that
triggered the action.
// Create an action
Action action = new AbstractAction("Action Label") {
// This method is called when the action is triggered
public void actionPerformed(ActionEvent evt) {
Component c = (Component)[Link]();
// Get the frame
Component frame = [Link](c);
// Hide the frame
[Link](false);
}
};
jlabel
8. Creating a JLabel Component
// The text is left-justified and vertically centered
JLabel label = new JLabel("Text Label");
// The text is horizontally and vertically centered
label = new JLabel("Text Label", [Link]);
// The text is right-justified and vertically centered
label = new JLabel("Text Label", [Link]);
// The text is left-justified and top-aligned
label = new JLabel("Text Label", [Link]);
[Link]([Link]);
// The text is right-justified and top-aligned
label = new JLabel("Text Label", [Link]);
[Link]([Link]);
// The text is left-justified and bottom-aligned
label = new JLabel("Text Label", [Link]);
[Link]([Link]);
// The text is right-justified and bottom-aligned
label = new JLabel("Text Label", [Link]);
[Link]([Link]);
9. Adding an Icon to a JLabel Component
This example creates a JLabel component with an icon.
// Fetch icon
Icon icon = new ImageIcon("[Link]");
// Create a label with text and an icon; the icon appears to the
left of the text
JLabel label = new JLabel("Text Label", icon, [Link]);
// Create a label with only an icon
label = new JLabel(icon);
This example adds or replaces the icon in an existing JLabel component:
// Add an icon to an existing label
[Link](icon);
The methods to control the position of the icon and text within a JLabel
component are identical to those of a JButton.
10. Setting the Focus of a JTextField Component Using a JLabel
Component
This example associates a label with a text field using setLabelFor(). A mnemonic is
set on the label. When the mnemonic keystroke is pressed, the text field will gain the
focus.
In the following example, when ALT-L is pressed, the text field gains the focus.
// Create text field
JTextField textfield = new JTextField(25);
// Create label and associate with text field
JLabel label = new JLabel("Text Label");
[Link](KeyEvent.VK_L);
[Link](textfield);
11. Adding Drag-and-Drop Support to a JLabel Component
This example demonstrates how to modify a label component so that its text can be
dragged and dropped to another component.
// Create a label
JLabel label = new JLabel("Label Text");
// Specify that the label's text property be transferable; the value
of
// this property will be used in any drag-and-drop involving this
label
final String propertyName = "text";
[Link](new TransferHandler(propertyName));
// Listen for mouse clicks
[Link](new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
JComponent comp = (JComponent)[Link]();
TransferHandler th = [Link]();
// Start the drag operation
[Link](comp, evt, [Link]);
}
});
jbutton
12. Creating a JButton Component
Although it is possible to create a button with just a label, it is highly recommended to
use an action to create a button. The action can then be shared by other components such
as a toolbar.
// Create an action
Action action = new AbstractAction("Button Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action...
}
};
// Create the button
JButton button = new JButton(action);
13. Changing the Label of a JButton Component
// To create a button,
// Change the label
[Link]("New Label");
// Remove the label; this is useful for a button with only an icon
[Link](null);
14. Creating a Multiline Label for a JButton Component
A button label can show simple HTML tags when surrounded by the tags <HTML> and
</HTML>. This example shows how to create multiple lines by using the <BR> tag. See the
[Link] class documentation for a list of supported tags.
String label = "<html>"+"This is a"+"<br>"+"swing button"+"</html>";
// Create an action with the label
Action action = new AbstractAction(label) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Create the button
JButton button = new JButton(action);
By default, the lines are left justified. This label text will center the lines:
[Link]("<html><center>"+"This is a"+"<br>"+"swing
button"+"</center></html>");
This label text italicizes the second line:
[Link]("<html>"+"This is a"+"<br><i>"+"swing
button"+"</i></html>");
15. Adding an Icon to a JButton Component
If the action used to create the button contains an icon, the button will be created using
that icon. The icon will appear to the left of the text; to change the icon's position, .
// Retrieve the icon
Icon icon = new ImageIcon("[Link]");
// Create an action with an icon
Action action = new AbstractAction("Button Label", icon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Create the button; the icon will appear to the left of the label
JButton button = new JButton(action);
If the action does not have an icon or a different icon must be used, add or change the
icon using setIcon():
// Add or change the icon; it will appear to the left of the text
[Link](icon);
// Set to null to remove icon
[Link](null);
16. Moving the Icon in a JButton Component
There are two methods for controlling the position of the text relative to the icon - -
setVerticalTextPosition() and setHorizontalTextPosition(). There are three
settings for each axis, which allows for a total of nine positions.
To control the gap between the text and icon, Note: Not all placements are possible. For
example, it is not possible to place the text above the icon with their left edges aligned.
The nine possible placements are demonstrated below.
// To create a button with an icon,
// Place text over center of icon; they both occupy the same space
[Link]([Link]);
[Link]([Link]);
// Place text above icon
[Link]([Link]);
[Link]([Link]);
// Place text below icon
[Link]([Link]);
[Link]([Link]);
// Place text to the left of icon, vertically centered
[Link]([Link]);
[Link]([Link]);
// Place text to the left of icon and align their tops
[Link]([Link]);
[Link]([Link]);
// Place text to the left of icon and align their bottoms
[Link]([Link]);
[Link]([Link]);
// Place text to the right of icon, vertically centered
[Link]([Link]);
[Link]([Link]);
// Place text to the right of icon and align their tops
[Link]([Link]);
[Link]([Link]);
// Place text to the right of icon and align their bottoms
[Link]([Link]);
[Link]([Link]);
17. Moving the Label/Icon Pair in a JButton Component
When the size of the button component is larger than its contents, the label and icon are
always kept together. In fact, the gap size determines the fixed distance between them.
Using two alignment methods, you can place the label/icon pair in one of nine possible
locations.
// To create a button with an icon,
// Place the contents in the nw corner
[Link]([Link]);
[Link]([Link]);
// Place the contents centered at the top
[Link]([Link]);
[Link]([Link]);
// Place the contents in the ne corner
[Link]([Link]);
[Link]([Link]);
// Place the contents in the sw corner
[Link]([Link]);
[Link]([Link]);
// Place the contents centered at the bottom
[Link]([Link]);
[Link]([Link]);
// Place the contents in the se corner
[Link]([Link]);
[Link]([Link]);
// Place the contents vertically centered on the left
[Link]([Link]);
[Link]([Link]);
// Place the contents directly in the center
[Link]([Link]);
[Link]([Link]);
// Place the contents vertically centered on the right
[Link]([Link]);
[Link]([Link]);
18. Setting the Gap Size Between the Label and Icon in a JButton
Component
// To create a button with an icon,
// Get gap size; default is 4
int gapSize = [Link]();
// Set gap size
[Link](8);
19. Adding a Disabled Icon to a JButton Component
By default, when a button is disabled, it automatically generates a grayed-out version of
the installed icon. However, it is possible to set a specific icon to use when the button is
disabled.
// To create a button with an icon
// Icon will appear gray
[Link](false);
// Set a disabled version of icon
Icon disabledIcon = new ImageIcon("[Link]");
[Link](disabledIcon);
// To remove the disabled version of the icon, set to null
[Link](null);
// If original icon is set as the disabled icon, disabling
// the button will have no effect on the icon
[Link](icon);
20. Adding a Rollover and Pressed Icon to a JButton Component
The rollover icon is displayed when the cursor is moved over the button. If no rollover
icon is set, the default icon is displayed when the cursor is moved over the button.
The pressed icon is displayed when the button is armed (i.e., the mouse button is down
while the cursor is on the button). If no pressed icon is set, the default icon is displayed
when the button is armed.
The rollover and pressed icons are never displayed if the button is disabled.
// To create a button with an icon,
// Add rollover icon
Icon rolloverIcon = new ImageIcon("[Link]");
[Link](rolloverIcon);
// Add pressed icon
Icon pressedIcon = new ImageIcon("[Link]");
[Link](pressedIcon);
// To remove rollover icon, set to null
[Link](null);
// To remove pressed icon, set to null
[Link](null);
jcheckbox
21. Creating a JCheckbox Component
By default, the state of the checkbox is off; to change the state,. Also by default, the
checkbox is left-justified and vertically centered. The methods to control the text
alignment are identical to those of a JButton
// Create an action
Action action = new AbstractAction("CheckBox Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
JCheckBox cb = (JCheckBox)[Link]();
// Determine status
boolean isSel = [Link]();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
}
};
// Create the checkbox
JCheckBox checkBox = new JCheckBox(action);
23. Getting and Setting the State of a JCheckbox Component
// To create a checkbox
// Get the current state of the checkbox
boolean b = [Link]();
// Set the state of the checkbox to off
[Link](false);
// Set the state of the checkbox to on
[Link](true);
24. Adding an Icon to the Label of a JCheckBox Component
Unlike a button, setIcon() does not add an icon to the text label. Rather, in a checkbox,
the method is used to customize the icons used to depict its state. However, by using the
HTML capabilities in a label, it is possible to add an icon to the label without affecting
the state-depicting icons. This example demonstrates the technique.
// Define an HTML fragment with an icon on the left and text on the
right.
// The elements are embedded in a 3-column table.
String label = "<html><table cellpadding=0><tr><td><img src=file:"
// The location of the icon
+ [Link]"
+ "/></td><td width="
// The gap, in pixels, between icon and text
+ 3
+ "><td>"
// Retrieve the current label text
+ [Link]()
+ "</td></tr></table></html>";
// Add the icon
[Link](label);
25. Customizing the Icons in a JCheckBox Component
The icons used to depict the selected state of a checkbox component can be customized.
The simplest customization requires two icons, one to depict the selected state and one to
depict the unselected state.
// Set the unselected state icon
Icon unselIcon = new ImageIcon("[Link]");
[Link](unselIcon);
// Set the selected state icon
Icon selIcon = new ImageIcon("[Link]");
[Link](selIcon);
If the checkbox is disabled, grayed out icons are automatically generated for the
customized icons. Here's how to customize these disabled icons:
// Set the unselected state icon
Icon unselDisIcon = new ImageIcon("[Link]");
[Link](unselDisIcon);
// Set the selected state icon
Icon selDisIcon = new ImageIcon("[Link]");
[Link](selDisIcon);
By default, when the user clicks on a checkbox, the pressed icon (if set) is displayed.
Here's how to set it:
Icon pressedIcon = new ImageIcon("[Link]");
[Link](pressedIcon);
Finally, it is possible to display an icon when the cursor is moved over the checkbox.
This is called the rollover icon.
Icon rollIcon = new ImageIcon("[Link]");
[Link](rollIcon);
jcombobox
26. Creating a JComboBox Component
// Create a read-only combobox
String[] items = {"item1", "item2"};
JComboBox readOnlyCB = new JComboBox(items);
By default, a combobox only allows the user to select from a predefined list of values.
The combobox can be made editable which not only allows the user to select from the
predefined list but also to type in any string.
// Create an editable combobox
items = new String[]{"item1", "item2"};
JComboBox editableCB = new JComboBox(items);
[Link](true);
27. Getting and Setting the Selected Item in a JComboBox Component
// Create a read-only combobox
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
// Get current value
Object obj = [Link](); // item1
// Set a new value
[Link]("item2");
obj = [Link](); // item2
// If the new value is not in the list of valid items, the call is
ignored
[Link]("item3");
obj = [Link](); // item2
// However, if the combobox is editable, the new value can be any
value
[Link](true);
[Link]("item3");
obj = [Link](); // item3
28. Getting the Items in a JComboBox Component
// Create a read-only combobox
String[] items = {"item1", "item2", "item3"};
JComboBox cb = new JComboBox(items);
// Get number of items
int num = [Link]();
// Get items
for (int i=0; i<num; i++) {
Object item = [Link](i);
}
// [item1, item2, item3]
29. Adding and Removing an Item in a JComboBox Component
There is no method for replacing an item. To replace an item, first remove the item and
then insert the new one.
// Create a read-only combobox; the combobox is read-only
// in that it does not allow the user to type in a new item.
// The combobox still allows programmatic changes to its items.
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
// Add an item to the start of the list
[Link]("item0", 0);
// Add an item after the first item
[Link]("item0.5", 1);
// Add an item to the end of the list
[Link]("item3");
// Remove first item
[Link](0);
// Remove the last item
[Link]([Link]()-1);
// Remove all items
[Link]();
30. Selecting an Item in a JComboBox Component with Multiple
Keystrokes
By default, when the user types a keystroke in a read-only combobox and an item in the
combobox starts with the typed keystroke, the combobox will select that item. This
behavior is not ideal if there are multiple items that start with the same letter.
This example demonstrates how to customize a combobox so that it will select an item
based on multiple keystrokes. More specifically, if a keystroke is typed within 300
milliseconds of the previous keystroke, the new keystroke is appended to the previous
keystroke, and the combobox will select an item that starts with both keystrokes.
// Create a read-only combobox
String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
JComboBox cb = new JComboBox(items);
// Install the custom key selection manager
[Link](new MyKeySelectionManager());
// This key selection manager will handle selections based on
multiple keys.
class MyKeySelectionManager implements [Link]
{
long lastKeyTime = 0;
String pattern = "";
public int selectionForKey(char aKey, ComboBoxModel model) {
// Find index of selected item
int selIx = 01;
Object sel = [Link]();
if (sel != null) {
for (int i=0; i<[Link](); i++) {
if ([Link]([Link](i))) {
selIx = i;
break;
}
}
}
// Get the current time
long curTime = [Link]();
// If last key was typed less than 300 ms ago, append to
current pattern
if (curTime - lastKeyTime < 300) {
pattern += ("" + aKey).toLowerCase();
} else {
pattern = ("" + aKey).toLowerCase();
}
// Save current time
lastKeyTime = curTime;
// Search forward from current selection
for (int i=selIx+1; i<[Link](); i++) {
String s =
[Link](i).toString().toLowerCase();
if ([Link](pattern)) {
return i;
}
}
// Search from top to current selection
for (int i=0; i<selIx ; i++) {
if ([Link](i) != null) {
String s =
[Link](i).toString().toLowerCase();
if ([Link](pattern)) {
return i;
}
}
}
return -1;
}
}
31. Determining If the Menu of a JComboBox Component Is Visible
// Create a read-only combobox
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
// Determine if the menu is visible
boolean isVisible = [Link]();
32. Displaying the Menu in a JComboBox Component Using a Keystroke
By default, typing a key in a read-only combobox selects an item that starts with the
typed key. This example demonstrates how to display the drop-down menu when a key is
typed.
// Create a read-only combobox
String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat", "Cow"};
JComboBox cb = new JComboBox(items);
// Create and register the key listener
[Link](new MyKeyListener());
// This key listener displays the menu when a key is pressed.
// To display the menu only if the pressed key matches or does not
match an item,
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
JComboBox cb = (JComboBox)[Link]();
// Get pressed character
char ch = [Link]();
// If not a printable character, return
if (ch != KeyEvent.CHAR_UNDEFINED) {
[Link]();
}
}
}
33. Displaying the Menu in a JComboBox Component Using a Keystroke
If the Selected Item Is Not Unique
This example registers a key listener in a read-only combobox that displays the menu if
the newly selected item is not unique.
// Create a read-only combobox
String[] items = {"Ant", "Ape", "Bat", "Boa", "Cat"};
JComboBox cb = new JComboBox(items);
// Create and register the key listener
[Link](new MyKeyListener());
// This key listener displays the menu only if the pressed key
// does not select a new item or if the selected item is not unique.
class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
JComboBox cb = (JComboBox)[Link]();
// At this point, the selection in the combobox has already
been
// changed; get the index of the new selection
int curIx = [Link]();
// Get pressed character
char ch = [Link]();
// Get installed key selection manager
[Link] ksm =
[Link]();
if (ksm != null) {
// Determine if another item has the same prefix
int ix = [Link](ch, [Link]());
boolean noMatch = ix < 0;
boolean uniqueItem = ix == curIx;
// Display menu if no matching items or the if the
selection is not unique
if (noMatch || !uniqueItem) {
[Link]();
}
}
}
}
34. Setting the Number of Visible Items in the Menu of a JComboBox
Component
By default, the menu of a combobox only shows eight items. If there are more items in
the menu, a scrollbar is automatically created. To change the default of eight, use
[Link]().
// Create a read-only combobox with lots of items
String[] items = new String[50];
for (int i=0; i<[Link]; i++) {
items[i] = "" + [Link]();
}
JComboBox cb = new JComboBox(items);
// Retrieve the current max visible rows
int maxVisibleRows = [Link]();
// Change the current max visible rows
maxVisibleRows = 20;
[Link](maxVisibleRows);
35. Listening for Changes to the Selected Item in a JComboBox
Component
Item events are generated whenever the selected item changes. These events are
generated even while the user is moving through items in the displayed popup menu. If
the combobox is editable, this event does not indicate whether the new item is taken from
the predefined list or not. If this information is necessary
// Create an editable combobox
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
[Link](true);
// Create and register listener
MyItemListener actionListener = new MyItemListener();
[Link](actionListener);
class MyItemListener implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox)[Link]();
// Get the affected item
Object item = [Link]();
if ([Link]() == [Link]) {
// Item was just selected
} else if ([Link]() == [Link]) {
// Item is no longer selected
}
}
}
36. Listening for Action Events from a JComboBox Component
Action events are generated whenever the selected item changes. These events are
generated even while the user is moving through items in the displayed popup menu.
Unlike item events action events are generated even if the new item is the same as the
old item.
// Create component
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
[Link](true);
// Create and register listener
MyActionListener actionListener = new MyActionListener();
[Link](actionListener);
class MyActionListener implements ActionListener {
// Retain the previously selected item in order to determine
whether
// the new item is the same
Object oldItem;
// This method is called whenever the user or program changes
the selected item.
// Note: The new item may be the same as the previous item.
public void actionPerformed(ActionEvent evt) {
JComboBox cb = (JComboBox)[Link]();
// Get the new item
Object newItem = [Link]();
// Determine if different from previously selected item
boolean same = [Link](oldItem);
oldItem = newItem;
if ("comboBoxEdited".equals([Link]())) {
// User has typed in a string; only possible with an
editable combobox
} else if ("comboBoxChanged".equals([Link]()))
{
// User has selected an item; it may be the same item
}
}
}
37. Determining When the Menu of a JComboBox Component Is
Displayed
// Create component
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
[Link](true);
// Create and register listener
MyPopupMenuListener actionListener = new MyPopupMenuListener();
[Link](actionListener);
class MyPopupMenuListener implements PopupMenuListener {
// This method is called just before the menu becomes visible
public void popupMenuWillBecomeVisible(PopupMenuEvent evt) {
JComboBox cb = (JComboBox)[Link]();
}
// This method is called just before the menu becomes hidden
public void popupMenuWillBecomeInvisible(PopupMenuEvent evt) {
JComboBox cb = (JComboBox)[Link]();
}
// This method is called when menu is hidden because the user
cancelled it
public void popupMenuCanceled(PopupMenuEvent evt) {
JComboBox cb = (JComboBox)[Link]();
}
}
jradiobutton
38. Creating a JRadioButton Component
// Create an action for each radio button
Action action1 = new AbstractAction("RadioButton Label1") {
// This method is called whenever the radio button is pressed,
// even if it is already selected; this method is not called
// if the radio button was selected programmatically
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
Action action2 = new AbstractAction("RadioButton Label2") {
// See above
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Create the radio buttons using the actions
JRadioButton b1 = new JRadioButton(action1);
JRadioButton b2 = new JRadioButton(action2);
// Associate the two buttons with a button group
ButtonGroup group = new ButtonGroup();
[Link](b1);
[Link](b2);
// Neither radio button is selected; to select a radio button,
39. Selecting a JRadioButton Component in a Button Group
// To create a radio button and button group,
// Select the radio button; the currently selected radio button is
deselected.
// This operation does not cause any action events to be fired.
ButtonModel model = [Link]();
[Link](model, true);
40. Determining the Selected JRadioButton in a Button Group
When you ask a button group for the currently selected radio button, it returns the
selected radio button's model (rather than the selected radio button itself). Fortunately,
the button group maintains the list of buttons and so you can iterate over this list looking
for one with the same model.
// This method returns the selected radio button in a button group
public static JRadioButton getSelection(ButtonGroup group) {
for (Enumeration e=[Link](); [Link](); ) {
JRadioButton b = (JRadioButton)[Link]();
if ([Link]() == [Link]()) {
return b;
}
}
return null;
}
41. Determining If a JRadioButton Component Is Selected
// This method returns true if btn is selected; false otherwise
public static boolean isSelected(JRadioButton btn) {
DefaultButtonModel model = (DefaultButtonModel)[Link]();
return [Link]().isSelected(model);
}
42. Adding an Icon to the Label of a JRadioButton Component
Unlike a JButton, setIcon() does not add an icon to the text label.
Rather, in a radio button, the method is used to customize the icons
used to depict its state. However, by using the HTML capabilities in a
label, it is possible to add an icon to the label without affecting the
state-depicting icons. This technique is identical to the one used for
checkboxes.
43. Customizing the Icons in a JRadioButton Component
The icons used to depict the selected state of a radio button can be
customized. The customization of radio button icons is identical to the
customization of checkboxes.
JLIST
44. Creating a JList Component
By default, a list allows more than one item to be selected. Also, the selected items need
not be contiguous.
A list selection event is fired when the set of selected items is changed .
// Create a list with some items
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
The items can be arbitrary objects. The toString() method of the objects is displayed in
the list component.
// Create a list with two items - "123" and "Sun May 19 [Link] PDT
2002"
Object[] items2 = {new Integer(123), new [Link]()};
list = new JList(items2);
By default, a list does not automatically display a scrollbar when there are more items
than can be displayed. The list must be wrapped in a scroll pane:
JScrollPane scrollingList = new JScrollPane(list);
45. Setting the Dimensions of an Item in a JList Component
By default, the width of the list is determined by the longest item and the height is
determined by the number of visible lines multiplied by the tallest item. This example
demonstrates how to override these values.
// Create a list
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Set the item width
int cellWidth = 200;
[Link](cellWidth);
// Set the item height
int cellHeight = 18;
[Link](cellHeight);
It is also possible to set the item dimensions using a sample value:
String protoCellValue = "My Sample Item Value";
[Link](protoCellValue);
46. Setting a Tool Tip for an Item in a JList Component
// Create a list, overriding the getToolTipText() method
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items) {
// This method is called as the cursor moves within the list.
public String getToolTipText(MouseEvent evt) {
// Get item index
int index = locationToIndex([Link]());
// Get item
Object item = getModel().getElementAt(index);
// Return the tool tip text
return "tool tip for "+item;
}
};
47. Getting the Items in a JList Component
// Create a list
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Get number of items in the list
int size = [Link]().getSize(); // 4
// Get all item objects
for (int i=0; i<size; i++) {
Object item = [Link]().getElementAt(i);
}
These methods are used to find an item:
// The prefix is case-insensitive
String prefix = "b";
// Search forward, starting from index 0, looking for an item that
starts with "b"
int start = 0;
[Link] direction =
[Link];
int itemIx = [Link](prefix, start, direction);
// Search backward, starting from the last item, looking for an item
that starts with "b"
start = [Link]().getSize()-1;
direction = [Link];
itemIx = [Link](prefix, start, direction);
These methods can be used to find the range of visible items:
// Get number of visible items
int visibleSize = [Link]();
// Get index of first visible item
itemIx = [Link]();
if (itemIx < 0) {
// List is either not visible or there are no items
}
// Get index of last visible item
itemIx = [Link]();
if (itemIx < 0) {
// List is either not visible or there are no items
}
48. Adding and Removing an Item in a JList Component
The default model for a list does not allow the addition and removal of items. The list
must be created with a DefaultListModel.
// Create a list that allows adds and removes
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
// Initialize the list with items
String[] items = {"A", "B", "C", "D"};
for (int i=0; i<[Link]; i++) {
[Link](i, items[i]);
}
// Append an item
int pos = [Link]().getSize();
[Link](pos, "E");
// Insert an item at the beginning
pos = 0;
[Link](pos, "a");
This method replaces an item:
// Replace the 2nd item
pos = 1;
[Link](pos, "b");
These methods are used to remove items:
// Remove the first item
pos = 0;
[Link](pos);
// Remove the last item
pos = [Link]()-1;
if (pos >= 0) {
[Link](pos);
}
// Remove all items
[Link]();
49. Getting the Selected Items in a JList Component
The following methods return the indices of the selected items:
// To create a list
// Get the index of all the selected items
int[] selectedIx = [Link]();
// Get all the selected items using the indices
for (int i=0; i<[Link]; i++) {
Object sel = [Link]().getElementAt(selectedIx[i]);
}
// Get the index of the first selected item
int firstSelIx = [Link]();
// Get the index of the last selected item
int lastSelIx = [Link]();
// Determine if the third item is selected
int index = 2;
boolean isSel = [Link](index);
// Determine if there are any selected items
boolean anySelected = ![Link]();
The following methods return the selected item objects:
// Get the first selected item
Object firstSel = [Link]();
// Get all selected items without using indices
Object[] selected = [Link]();
50. Setting the Selected Items in a JList Component
List selection events are fired when the following methods are used to change the set of
selected items.
// Create a list and get the model
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Select the second item
int start = 1;
int end = 1;
[Link](start, end); // B
// Select the first 3 items
start = 0;
end = 2;
[Link](start, end); // A, B, C
// Select all the items
start = 0;
end = [Link]().getSize()-1;
if (end >= 0) {
[Link](start, end); // A, B, C, D
}
// Clear all selections
[Link]();
// Select the first item
start = 0;
end = 0;
[Link](start, end); // A
// Add another selection - the third item
start = 2;
end = 2;
[Link](start, end); // A, C
// Deselect the first item
start = 0;
end = 0;
[Link](start, end); // C
// Select a single item
boolean scrollIntoView = true;
[Link]("B", scrollIntoView); // B
51. Setting the Selection Mode of a JList Component
// The default mode is MULTIPLE_INTERVAL_SELECTION
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Get the current selection model mode
int mode = [Link](); // MULTIPLE_INTERVAL_SELECTION
// Only one item can be selected
[Link](DefaultListSelectionModel.SINGLE_SELECTION);
// The selected items must be in a contiguous range
[Link](DefaultListSelectionModel.SINGLE_INTERVAL_SELECTIO
N);
// Multiple ranges of selected items are allowed
[Link](DefaultListSelectionModel.MULTIPLE_INTERVAL_SELECT
ION);
52. Arranging Items in a JList Component
By default, the items in a list are arranged vertically, in a single column, as in:
item1
item2
...
It is possible to arrange the items left-to-right and top-to-bottom, as in:
item1 item2
item3 item4
item5 ...
This example creates and configures a list that displays its items left-to-right and top-to-
bottom. Note that the number of columns can change as the width of the list changes.
// Create a scrollable list
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JScrollPane scrollingList = new JScrollPane(list);
// The default layout orientation is [Link]
int orient = [Link]();
// Change the layout orientation to left-to-right, top-to-bottom
[Link](JList.HORIZONTAL_WRAP);
The items can also be arranged top-to-bottom and left-to-right, as in:
item1 item4
item2 item5
item3 ...
This example changes the layout orientation so that its items are displayed top-to-bottom
and left-to-right.
// Change orientation to top-to-bottom, left-to-right layout
[Link](JList.VERTICAL_WRAP);
With some look and feels, a list is set to display a fixed number of rows. In order to make
the number of visible rows dependent on the height of the list, the visibleRowCount
property must be set to 0:
// Make the number of rows dynamic
[Link](0);
54. Detecting Double and Triple Clicks on an Item in a JList Component
// Create a list
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Add a listener for mouse clicks
[Link](new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
JList list = (JList)[Link]();
if ([Link]() == 2) { // Double-click
// Get item index
int index = [Link]([Link]());
} else if ([Link]() == 3) { // Triple-click
// Get item index
int index = [Link]([Link]());
// Note that this list will receive a double-click event
before this triple-click event
}
}
});
55. Listening for Changes to the Selection in a JList Component
When the set of selected items is changed, either by the user or programmatically, a list
selection event is fired.
// Create a list
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
// Register a selection listener
[Link](new MyListSelectionListener());
class MyListSelectionListener implements ListSelectionListener {
// This method is called each time the user changes the set of
selected items
public void valueChanged(ListSelectionEvent evt) {
// When the user release the mouse button and completes the
selection,
// getValueIsAdjusting() becomes false
if (![Link]()) {
JList list = (JList)[Link]();
// Get all selected items
Object[] selected = [Link]();
// Iterate all selected items
for (int i=0; i<[Link]; i++) {
Object sel = selected[i];
}
}
}
}
56. Listening for Changes to the Items in a JList Component
When the set of items in a list component is changed, a list data event is fired.
// Create a list that allows adds and removes;
// Register a list data listener
DefaultListModel model = (DefaultListModel)[Link]();
[Link](new MyListDataListener());
class MyListDataListener implements ListDataListener {
// This method is called when new items have been added to the
list
public void intervalAdded(ListDataEvent evt) {
DefaultListModel model = (DefaultListModel)[Link]();
// Get range of new items
int start = evt.getIndex0();
int end = evt.getIndex1();
int count = end-start+1;
// Get new items
for (int i=start; i<=end; i++) {
Object item = [Link](i);
}
}
// This method is called when items have been removed from the
list
public void intervalRemoved(ListDataEvent evt) {
// Get range of removed items
int start = evt.getIndex0();
int end = evt.getIndex1();
int count = end-start+1;
// The removed items are not available
}
// This method is called when items in the list are replaced
public void contentsChanged(ListDataEvent evt) {
DefaultListModel model = (DefaultListModel)[Link]();
// Get range of changed items
int start = evt.getIndex0();
int end = evt.getIndex1();
int count = end-start+1;
// Get changed items
for (int i=start; i<=end; i++) {
Object item = [Link](i);
}
}
}
JSPINNER
57. Creating a JSpinner Component
This example demonstrates how to build three kinds of spinners. A number spinner:
// Create a number spinner
JSpinner spinner = new JSpinner();
// Set its value
[Link](new Integer(100));
A list spinner:
// Create a list spinner
SpinnerListModel listModel = new SpinnerListModel(
new String[]{"red", "green", "blue"});
spinner = new JSpinner(listModel);
// Set its value
[Link]("blue");
A date spinner:
// Create a date spinner
SpinnerDateModel dateModel = new SpinnerDateModel();
spinner = new JSpinner(dateModel);
// Set its value to jan 1 2000
Calendar calendar = new GregorianCalendar(2000, [Link],
1);
[Link]([Link]());
58. Creating an Hour JSpinner Component
// Create a calendar object and initialize to a particular hour if
desired
Calendar calendar = new GregorianCalendar();
[Link](Calendar.HOUR_OF_DAY, 13); // 1pm
// Create a date spinner that controls the hours
SpinnerDateModel dateModel = new SpinnerDateModel(
[Link](), null, null, Calendar.HOUR_OF_DAY);
JSpinner spinner = new JSpinner(dateModel);
// Get the date formatter
JFormattedTextField tf =
(([Link])[Link]()).getTextField();
DefaultFormatterFactory factory =
(DefaultFormatterFactory)[Link]();
DateFormatter formatter =
(DateFormatter)[Link]();
// Change the date format to only show the hours
[Link](new SimpleDateFormat("hh:00 a"));
// Or use 24 hour mode
[Link](new SimpleDateFormat("HH:00 a"));
59. Disabling Keyboard Editing in a JSpinner Component
// Create a nummber spinner
JSpinner spinner = new JSpinner();
// Disable keyboard edits in the spinner
JFormattedTextField tf =
(([Link])[Link]()).getTextField();
[Link](false);
// The previous call sets the background to a disabled
// color (usually gray). To change this disabled color,
// reset the background color.
[Link]([Link]);
// The value of the spinner can still be programmatically changed
[Link](new Integer(100));
60. Limiting the Values in a Number JSpinner Component
// Create a number spinner that only handles values in the range
[0,100]
int min = 0;
int max = 100;
int step = 5;
int initValue = 50;
SpinnerModel model = new SpinnerNumberModel(initValue, min, max,
step);
JSpinner spinner = new JSpinner(model);
61. Setting the Margin Space on a JSpinner Component
// Create a number spinner
JSpinner spinner = new JSpinner();
// Get the text field
JFormattedTextField tf =
(([Link])[Link]()).getTextField();
// Set the margin (add two spaces to the left and right side of the
value)
int top = 0;
int left = 2;
int bottom = 0;
int right = 2;
Insets insets = new Insets(top, left, bottom, right);
[Link](insets);
62. Customizing the Editor in a JSpinner Component
This example replaces the default editor (a JFormattedTextField) in a spinner
component with a custom editor. The custom editor is simply a panel that displays a
color. The name of the color to display is stored in a SpinnerListModel.
// Create a color spinner
ColorSpinner spinner = new ColorSpinner(
new String[]{"red", "green", "blue"});
// Change the selected color
[Link]("blue");
public class ColorSpinner extends JSpinner {
public ColorSpinner(String[] colorNames) {
super();
setModel(new SpinnerListModel(colorNames));
setEditor(new Editor(this));
}
public class Editor extends JPanel implements ChangeListener {
int preferredWidth = 30;
int preferredHeight = 16;
Editor(JSpinner spinner) {
// Add the listener
[Link](this);
// Set the preferred size
setPreferredSize(new Dimension(preferredWidth,
preferredHeight));
// Display the current color
setColor((String)[Link]());
}
// Handles changes to the value stored in the model
public void stateChanged(ChangeEvent evt) {
JSpinner spinner = (JSpinner)[Link]();
// Get the new value
String value = (String)[Link]();
// Update the displayed color
setColor(value);
}
// Updates the displayed color to 'colorName' which must be
one
// of the predefined colors in [Link].
public void setColor(String colorName) {
try {
// Find the field and value of colorName
Field field =
[Link]("[Link]").getField(colorName);
Color color = (Color)[Link](null);
// Display the color
setBackground(color);
} catch (Exception e) {
}
}
}
64. Creating a SpinnerListModel That Loops Through Its Values
By default, if the user is browsing the values in a SpinnerListModel, the iteration stops
when either end is reached. This example demonstrates a subclass that allows the user to
continuously loop through the values.
SpinnerCircularListModel listModel = new SpinnerCircularListModel(
new String[]{"red", "green", "blue"});
JSpinner spinner = new JSpinner(listModel);
public class SpinnerCircularListModel extends SpinnerListModel {
public SpinnerCircularListModel(Object[] items) {
super(items);
}
// Returns the next value. If the current value is at the end
// of the list, returns the first value.
// There must be at least one item in the list.
public Object getNextValue() {
[Link] list = getList();
int index = [Link](getValue());
index = (index >= [Link]()-1) ? 0 : index+1;
return [Link](index);
}
// Returns the previous value. If the current value is at the
// start of the list, returns the last value.
// There must be at least one item in the list.
public Object getPreviousValue() {
[Link] list = getList();
int index = [Link](getValue());
index = (index <= 0) ? [Link]()-1 : index-1;
return [Link](index);
}
}
65. Listening for Changes to the Value in a JSpinner Component
// Create a nummber spinner
JSpinner spinner = new JSpinner();
// Add the listener
[Link](new SpinnerListener());
// Changing the value programmatically also fires an event
[Link](new Integer(100));
public class SpinnerListener implements ChangeListener {
public void stateChanged(ChangeEvent evt) {
JSpinner spinner = (JSpinner)[Link]();
// Get the new value
Object value = [Link]();
}
}
JSLIDER
66. Creating a JSlider Component
// Create a horizontal slider with min=0, max=100, value=50
JSlider slider = new JSlider();
// Create a horizontal slider with custom min and max; value is set
to the middle
int minimum = -255;
int maximum = 256;
slider = new JSlider(minimum, maximum);
// Create a horizontal slider with custom min, max, and value
int initValue = 0;
slider = new JSlider(minimum, maximum, initValue);
// Create a vertical slider with min=0, max=100, value=50
slider = new JSlider([Link]);
// Create a vertical slider with custom min, max, and value
slider = new JSlider([Link], minimum, maximum, initValue);
In addition to allowing the user to drag the slider, some look and feels allow the user
page the slider by a fixed amount. This amount is called the extent.
// Set an extent
int extent = 10;
[Link](extent);
For most look and feels, the slider appears as a knob on a track. In this case, it is possible
to hide the track:
[Link](false);
67. Getting and Setting the Values of a JSlider Component
// To create a slider
// Get the current value
int value = [Link]();
// Get the minimum value
int min = [Link]();
// Get the maximum value
int max = [Link]();
// Get the extent
int extent = [Link]();
// Change the minimum value
int newMin = 0;
[Link](newMin);
// Change the maximum value
int newMax = 256;
[Link](newMax);
// Set the value; the new value will be forced into the bar's range
int newValue = 33;
[Link](newValue);
// Set the extent
int newExtent = 10;
[Link](newExtent);
It is also possible to set all the values at once by using the model:
[Link]().setRangeProperties(newValue, newExtent, newMin,
newMax, false);
68. Setting the Orientation of a JSlider Component
Besides being either horizontal or vertical, a slider can also be inverted. An inverted
horizontal slider moves from right-to-left. An inverted vertical slider moves from top-to-
bottom.
// Create a horizontal slider that moves left-to-right
JSlider slider = new JSlider();
// Make the horizontal slider move right-to-left
[Link](true);
// Make it vertical and move bottom-to-top
[Link]([Link]);
[Link](false);
// Make it vertical and move top-to-bottom
[Link]([Link]);
[Link](true);
69. Showing Tick Marks on a JSlider Component
The slider supports two levels of tick marks, major and minor. Typically, the minor tick-
mark spacing is smaller than the major tick-mark spacing. Also, the minor tick-mark
spacing is a multiple of the major tick-mark spacing. However, the slider does not
enforce any of these constraints.
// Create a horizontal slider that moves left-to-right
JSlider slider = new JSlider();
// Determine if currently showing ticks
boolean b = [Link](); // false
// Show tick marks
[Link](true);
// Set major tick marks every 25 units
int tickSpacing = 25;
[Link](tickSpacing);
// Set minor tick marks every 5 units
tickSpacing = 5;
[Link](tickSpacing);
70. Showing Tick-Mark Labels on a JSlider Component
This example demonstrates how to display labels (numerical values) at the major ticks.
// Create a horizontal slider that moves left-to-right
JSlider slider = new JSlider();
// Set major tick marks every 25 units
int tickSpacing = 25;
[Link](tickSpacing);
// Determine if currently painting labels
boolean b = [Link](); // false
// Paint labels at the major ticks - 0, 25, 50, 75, and 100
[Link](true);
The slider allows you to use an arbitrary label at any particular major tick mark. This
example configures a slider that shows an icon at the minimum and maximum positions.
The component is only used to render the label and so it can be used at more than one
position. Unfortunately, it also means that if the component is interactive (e.g., a button),
it will not respond to mouse and keyboard gestures.
// Retrieve current table
[Link] table = [Link]();
// Create icon
ImageIcon icon = new ImageIcon("[Link]");
JLabel label = new JLabel(icon);
// Set at desired positions
[Link](new Integer([Link]()), label);
[Link](new Integer([Link]()), label);
// Force the slider to use the new labels
[Link](table);
71. Constraining JSlider Component Values to Tick Marks
By default, the slider can take on any value from the minimum to the maximum. It is
possible to configure the slider to allow only values at tick marks. This is done by calling
[Link](true).
The slider's minimum and minor tick-mark spacing determines what values are possible.
For example, if the minimum is 3 and the minor tick-mark spacing is 10, only the values,
3, 13, 23, and so forth, are allowed. If a minor tick-mark spacing has not been set, the
major tick-mark spacing is used. If neither a minor nor a major tick mark spacing has
been set, a tick-mark spacing of 1 is assumed.
Calling setSnapToTicks() also has the effect of causing the slider's knob to snap to the
closest tick mark whenever it is dragged or programmatically moved to a spot between
tick marks.
// Create a horizontal slider that moves left-to-right
JSlider slider = new JSlider();
// Set major tick marks every 25 units
int tickSpacing = 25;
[Link](tickSpacing);
// Set minor tick marks every 5 units
tickSpacing = 5;
[Link](tickSpacing);
// Show tick marks
[Link](true);
// Determine if currently snapping to tick marks
boolean b = [Link](); // false
// Snap to tick marks
[Link](true);
// Set to a spot between tick marks; the value moves to closest tick
mark
[Link](27);
int value = [Link](); // 25
72. Listening for Value Changes in a JSlider Component
// Create horizontal slider
JSlider slider = new JSlider();
// Register a change listener
[Link](new ChangeListener() {
// This method is called whenever the slider's value is changed
public void stateChanged(ChangeEvent evt) {
JSlider slider = (JSlider)[Link]();
if (![Link]()) {
// Get new value
int value = [Link]();
}
}
});
JPROGRESSBAR
73. Creating a JProgressBar Component
A progress bar is used to visually indicate how much a task has been progressed. A
progress bar can be oriented horizontally (left-to-right) or vertically (bottom-to-top). By
default, the orientation is horizontal.
// Create a horizontal progress bar
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
// Create a vertical progress bar
minimum = 0;
maximum = 100;
progress = new JProgressBar([Link], minimum,
maximum);
74. Creating a JProgressBar Component with an Unknown Maximum
A progress bar with an unknown maximum typically displays an animation until the task
is complete.
Note: The percentage display should not be enabled when the maximum is not known.
// Create a horizontal progress bar
int min = 0;
int max = 100;
JProgressBar progress = new JProgressBar(min, max);
// Play animation
[Link](true);
When information on the task's progress is available, the progress bar can be made
determinate:
int value = 33;
[Link](value);
[Link](false);
75. Getting and Setting the Values of a JProgressBar Component
// To create a progress bar,
// Get the current value
int value = [Link]();
// Get the minimum value
int min = [Link]();
// Get the maximum value
int max = [Link]();
// Change the minimum value
int newMin = 0;
[Link](newMin);
// Change the maximum value
int newMax = 256;
[Link](newMax);
// Set the value; the new value will be forced into the bar's range
int newValue = 33;
[Link](newValue);
It is also possible to set all the values at once by using the model:
[Link]().setRangeProperties(newValue, 0, newMin, newMax,
false
76. Displaying the Percentage Done on a JProgressBar Component
The progress bar offers the ability to display the actual value of the bar as a percentage.
This example demonstrates how to enable this display.
Note: The percentage display should not be enabled when the maximum is not known
// Create a horizontal progress bar
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
// Overlay a string showing the percentage done
[Link](true);
77. Listening for Value Changes in a JProgressBar Component
Whenever the value of a progress bar is changed, a change event is fired. In fact, the
event is also fired when the minimum or maximum values are changed. However, the
event does not specify which values were changed.
// Create a horizontal progress bar
int minimum = 0;
int maximum = 100;
JProgressBar progress = new JProgressBar(minimum, maximum);
[Link](new ChangeListener() {
// This method is called when the value, minimum, or maximum is
changed.
public void stateChanged(ChangeEvent evt) {
JProgressBar comp = (JProgressBar)[Link]();
// The old value is not available
// Get new values
int value = [Link]();
int min = [Link]();
int max = [Link]();
}
});
PROGRESS MONITOR
78. Creating a Progress Monitor Dialog
A common feature of a user interface is to show a progress dialog that visually displays
the progress of a long-running task. The dialog automatically disappears when the task is
done. The ProgressMonitor class is a convenient dialog that implements a progress
dialog.
The progress monitor contains a message which describes the long-running task. The
message does not change for the duration of the task. The progress monitor also allows
for a note which is a description of the current subtask. For example, if the task is
copying a set of files, the note could be the name of the current file being copied.
Note: A progress monitor should not be reused. The properties that control when the
dialog should appear are set when the monitor is constructed and cannot be reset.
// This message describes the task that is running
String message = "Description of Task";
// This string describes a subtask; set to null if not needed
String note = "subtask";
// Set the title of the dialog if desired
String title = "Task Title";
[Link]("[Link]", title);
// Create a progress monitor dialog.
// The dialog will use the supplied component's frame as the parent.
int min = 0;
int max = 100;
ProgressMonitor pm = new ProgressMonitor(component, message, note,
min, max);
As the task progresses, check to see if the task has been cancelled and if not, call
setProgress() and supply its current state.
// Check if the dialog has been cancelled
boolean cancelled = [Link]();
if (cancelled) {
// Stop task
} else {
// Set new state
[Link](newValue);
// Change the note if desired
[Link]("New Note");
}
79. Setting the Popup Delay of a Progress Monitor Dialog
By default, the progress monitor delays for a short period before it is displayed. There are
two properties that control when the dialog is displayed - - millisToPopup and
millisToDecideToPopup. The progress monitor computes a time-to-completion based
on the how fast the value changes. The dialog will not appear as long as the predicted
time-to-completion is less than millisToPopup. millisToDecideToPopup determines a
minimum time, since the progress monitor was created, before the dialog can appear.
In summary, the dialog is shown only if it has been millisToDecideToPopup
milliseconds after the progress monitor was created and the predicted time-to-completion
is greater than millisToPopup.
// Get delay based on time-to-completion
int millisToPopup = [Link](); // 2000
// Get minimum delay
int millisToDecideToPopup = [Link](); // 500
// To make progress monitor popup immediately, set both to 0
[Link](0);
[Link](0);
MENUS
80. Creating a JMenuBar, JMenu, and JMenuItem Component
When the user selects a menu item, it fires an action event.
// Create the menu bar
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("Menu Label");
[Link](menu);
// Create a menu item
JMenuItem item = new JMenuItem("Item Label");
[Link](actionListener);
[Link](item);
// Install the menu bar in the frame
[Link](menuBar);
81. Separating Menu Items in a Menu
A separator typically appears as a horizontal line. It is used to group related sets of menu
items in a menu.
// Create a menu
JMenu menu = new JMenu("Menu Label");
// Add a menu item
JMenuItem item1 = new JMenuItem("Item Label");
[Link](item1);
// Add separator
[Link](new JSeparator());
// Add another menu item
JMenuItem item2 = new JMenuItem("Item Label");
[Link](item2);
82. Creating a Popup Menu
final JPopupMenu menu = new JPopupMenu();
// Create and add a menu item
JMenuItem item = new JMenuItem("Item Label");
[Link](actionListener);
[Link](item);
// Set the component to show the popup menu
[Link](new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
if ([Link]()) {
[Link]([Link](), [Link](), [Link]());
}
}
public void mouseReleased(MouseEvent evt) {
if ([Link]()) {
[Link]([Link](), [Link](), [Link]());
}
}
});
83. Creating a Popup Menu with Nested Menus
final JPopupMenu popupMenu = new JPopupMenu();
// Create a submenu with items
JMenu submenu = new JMenu("SubMenu1");
[Link](action1);
[Link](action2);
// Add submenu to popup menu
[Link](submenu);
84. Forcing a Popup Menu to Be a Heavyweight Component
By default, Swing popup menus used by JMenu and JPopupMenu are lightweight. If
heavyweight components are used in the same frame, the popup menus may appear
behind the heavyweight components.
This example demonstrates how to force a JPopupMenu to use heavyweight components:
JPopupMenu popupMenu = new JPopupMenu();
// Retrieve current setting
boolean lwPopup = [Link](); // true
// Force the popup menu to use heavyweight components
[Link](false);
This example demonstrates how to force the popup menu of a JMenu to be heavyweight:
// Create a menu with a menu item
JMenu menu = new JMenu("Menu Label");
[Link](new JMenuItem("Item Label"));
// Retrieve current setting
lwPopup = [Link]().isLightWeightPopupEnabled(); // true
// Force the menu's popup menu to be heavyweight
[Link]().setLightWeightPopupEnabled(false);
This example configures all popup menus to be heavyweight:
// Retrieve current setting
lwPopup = [Link](); // true
// Globally use heavyweight components for all popup menus
[Link](false);
The currently selected menu or menu item in a JMenu or JPopupMenu is tracked by
MenuSelectionManager and can be retrieved by calling
[Link](). This method returns an array of
MenuElement objects, representing all the menu objects that are part of the selected menu
or menu item. For example, when a menu is opened in a menu bar, the sequence of
elements in the path is: JMenuBar, JMenu, and JPopupMenu. If a menu item in the open
menu is then selected, there will be fourth element, a JMenuItem.
The menu path also includes nested menus. For example, if the currently selected menu
item is part of a nested menu in a menu bar, the sequence of elements is: JMenuBar,
JMenu, JPopupMenu, JMenu, JPopupMenu, and JMenuItem. Note that a JMenu is always
followed by a JPopupMenu.
If a menu item in a popup menu is selected, the sequence of menu objects is simply
JPopupMenu and JMenuItem. If the menu item is part of a nest menu, the sequence is,
JPopupMenu, JMenu, JPopupMenu, and JMenuItem.
// Get the selected menu path
MenuElement[] path =
[Link]().getSelectedPath();
if ([Link] == 0) {
// No menus are opened or menu items selected
}
// Retrieve the labels of all the menu elements in the path
for (int i=0; i<[Link]; i++) {
Component c = path[i].getComponent();
if (c instanceof JMenuItem) {
JMenuItem mi = (JMenuItem)c;
String label = [Link]();
// Note: JMenu is a subclass of JMenuItem; also JMenuBar
does not have a label
}
}
85. Creating a Menu Item That Listens for Changes to Its Selection Status
A menu item can receive notification of selection changes by overriding its
menuSelectionChanged() method.
JMenuItem item = new JMenuItem("Label") {
// This method is called whenever the selection status of
// this menu item is changed
public void menuSelectionChanged(boolean isSelected) {
// Always forward the event
[Link](isSelected);
if (isSelected) {
// The menu item is selected
} else {
// The menu item is no longer selected
}
}
};
86. Listening for Changes to the Currently Selected Menu or Menu Item
The currently selected menu or menu item in a JMenu or JPopupMenu is tracked by
MenuSelectionManager. To receive notification of changes to the currently selected
menu or menu item, a change listener must be registered with the
MenuSelectionManager.
// Create a change listener and register with the menu selection
manager
[Link]().addChangeListener(
new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
// Get the selected menu or menu item
MenuSelectionManager msm =
(MenuSelectionManager)[Link]();
MenuElement[] path = [Link]();
// To interpret path, see
if ([Link] == 0) {
// All menus are hidden
}
}
}
);
JTOOLBAR
87. Creating a JToolbar Container
A toolbar can be either horizontal or vertical. When the orientation is horizontal, the
objects in the toolbar are displayed left-to-right. When the orientation is vertical, the
objects in the toolbar are displayed top-to-bottom. This orientation is automatically
changed when the toolbar is moved to the top or side of a container.
// Create a horizontal toolbar
JToolBar toolbar = new JToolBar();
// Create a vertical toolbar
toolbar = new JToolBar(null, [Link]);
// Get current orientation
int orient = [Link]();
The following code adds various buttons to the toolbar:
// Get icon
ImageIcon icon = new ImageIcon("[Link]");
// Create an action with an icon
Action action = new AbstractAction("Button Label", icon) {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
// Add a button to the toolbar; remove the label and margin before
adding
JButton c1 = new JButton(action);
[Link](null);
[Link](new Insets(0, 0, 0, 0));
[Link](c1);
// Add a toggle button; remove the label and margin before adding
JToggleButton c2 = new JToggleButton(action);
[Link](null);
[Link](new Insets(0, 0, 0, 0));
[Link](c2);
// Add a combobox
JComboBox c3 = new JComboBox(new String[]{"A", "B", "C"});
[Link]("XXXXXXXX"); // Set a desired width
[Link]([Link]());
[Link](c3);
If the toolbar is to be floatable , it must be added to a container with a BorderLayout.
// Add the toolbar to a frame
JFrame frame = new JFrame();
[Link]().add(toolbar, [Link]);
[Link]();
[Link](true);
88. Determining When a Floatable JToolBar Container Changes
Orientation
When the orientation of a toolbar is changed, either by the user or programmatically, the
toolbar fires a property change event.
// Create a floatable horizontal toolbar
JToolBar toolbar = new JToolBar();
// Register for orientation property change events
[Link](new
[Link]() {
// This method is called whenever the orientation of the toolbar
is changed
public void propertyChange([Link] evt) {
String propName = [Link]();
if ("orientation".equals(propName)) {
// Get the old orientation
Integer oldValue = (Integer)[Link]();
// Get the new orientation
Integer newValue = (Integer)[Link]();
if ([Link]() == [Link]) {
// toolbar now has horizontal orientation
} else {
// toolbar now has vertical orientation
}
}
}
});
89. Preventing a JToolbar Container from Floating
By default, a toolbar can float, that is, it can be dragged to a different edge in its container
or it can be moved into a top-level window.
// Create a horizontal toolbar
JToolBar toolbar = new JToolBar();
// Get current floatability
boolean b = [Link]();
// Disable floatability
[Link](false);
90. Highlighting Buttons in a JToolbar Container While Under the Cursor
By default, a button in a toolbar does not change its appearance when the cursor is over
the button. However, if the toolbar is in rollover mode, the buttons will highlight while
under a cursor.
// Create a horizontal toolbar
JToolBar toolbar = new JToolBar();
// Get current rollover mode
boolean b = [Link]();
// Enable rollover mode
[Link](true);
JSCROLLPANE
91. Creating a JScrollPane Container
The Swing components do not typically have scroll bars. In order to automatically
display scroll bars, you need to wrap the component in a scroll pane.
// Create a scrollable text area
JTextArea textArea = new JTextArea();
JScrollPane scrollableTextArea = new JScrollPane(textArea);
// Create a scrollable list
JList list = new JList();
JScrollPane scrollableList = new JScrollPane(list);
92. Setting the Scrollbar Policy of a JScrollPane Container
A scroll bar in a scroll pane can be set to appear only as needed, always appear, or never
appear. By default, both the vertical and horizontal scrollbars in a scroll pane appear only
when needed.
// Create a scrollable text area
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
// Get the default scrollbar policy
int hpolicy = [Link]();
// JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
int vpolicy = [Link]();
// JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;
// Make the scrollbars always appear
[Link](JScrollPane.HORIZONTAL_SCROLLBAR_ALWAY
S);
[Link](JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// Make the scrollbars never appear
[Link](JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
);
[Link](JScrollPane.VERTICAL_SCROLLBAR_NEVER);
93. Listening for Scrollbar Value Changes in a JScrollPane Container
A scrollbar in a scroll pane fires adjustment events whenever its value changes.
// Create a scrollable text area
JTextArea textArea = new JTextArea();
JScrollPane pane = new JScrollPane(textArea);
// Listen for value changes in the scroll pane's scrollbars
AdjustmentListener listener = new MyAdjustmentListener();
[Link]().addAdjustmentListener(listener);
[Link]().addAdjustmentListener(listener);
class MyAdjustmentListener implements AdjustmentListener {
// This method is called whenever the value of a scrollbar is
changed,
// either by the user or programmatically.
public void adjustmentValueChanged(AdjustmentEvent evt) {
Adjustable source = [Link]();
// getValueIsAdjusting() returns true if the user is
currently
// dragging the scrollbar's knob and has not picked a final
value
if ([Link]()) {
// The user is dragging the knob
return;
}
// Determine which scrollbar fired the event
int orient = [Link]();
if (orient == [Link]) {
// Event from horizontal scrollbar
} else {
// Event from vertical scrollbar
}
// Determine the type of event
int type = [Link]();
switch (type) {
case AdjustmentEvent.UNIT_INCREMENT:
// Scrollbar was increased by one unit
break;
case AdjustmentEvent.UNIT_DECREMENT:
// Scrollbar was decreased by one unit
break;
case AdjustmentEvent.BLOCK_INCREMENT:
// Scrollbar was increased by one block
break;
case AdjustmentEvent.BLOCK_DECREMENT:
// Scrollbar was decreased by one block
break;
case [Link]:
// The knob on the scrollbar was dragged
break;
}
// Get current value
int value = [Link]();
}
}
JSPLITPANE
94. Creating a JSplitPane Container
A split pane divides its space between two components. The split pane contains a divider
that allows the user to control the amount of space distributed to each component.
// Create a left-right split pane
JSplitPane hpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, rightComponent);
// Create a top-bottom split pane
JSplitPane vpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
topComponent, bottomComponent);
By default, when the divider is dragged, a shadow is displayed to indicate where the
divider would be when the mouse is released. It is possible for the split pane to
continuously move the divider and resize its child components while the user is dragging
the divider.
boolean b = [Link](); // false by default
// Set the split pane to continuously resize the child components
// which the divider is dragged
[Link](true);
The split pane supports a one-touch-expandable capability that allows the user to
conveniently move the divider to either end with a single click. This capability is enabled
by setting the following property:
b = [Link](); // false by default
[Link](true);
95. Getting the Setting the Children in a JSplitPane Container
// Create a left-right split pane
JSplitPane hpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, rightComponent);
// Create a top-bottom split pane
JSplitPane vpane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
topComponent, bottomComponent);
// Get the children from the horizontal split pane
leftComponent = [Link]();
rightComponent = [Link]();
// Get the children from the vertical split pane
topComponent = [Link]();
bottomComponent = [Link]();
// Replace the children in the horizontal split pane
[Link](comp1);
[Link](comp2);
// Replace the children in the vertical split pane
[Link](comp3);
[Link](comp4);
96. Distributing Space When a JSplitPane Container Is Resized
The weight of a split pane controls the behavior of the divider when the split pane is
resized. If the weight is 0, all extra space is given to the right or bottom component. If the
weight is 1, all extra space is given to the left or top component. A weight of .3 specifies
that the left or top component gets one-third of the extra space. The weight also
determines how the children lose space when the size of the split pane is reduced. For
example, a weight of 0 means that the left or top component does not lose any space.
The weight also controls the starting location of the divider. For example, if the weight
is .5, the divider is placed in the center.
// Create a left-right split pane
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, rightComponent);
// Get current weight
double weight = [Link](); // 0.0 by default
// Keep the size of the right component constant
weight = 1D;
[Link](weight);
// Split the space evenly
weight = .5D;
[Link](weight);
97. Getting and Setting the Divider Location in a JSplitPane Container
The location of a divider is measured in pixels from either the left edge (in the case of a
horizontal split pane) or the top edge (in the case of a vertical split pane).
There are two ways to set the location of the divider. The first is to specify an absolute
location based on the distance in pixels from the left or top edge. The second is to specify
a proportional location based on the distance from the left or top edge. For example, a
proportional location of 0 sets the divider at the left or top edge. A proportional location
of 1 sets the divider at the right or bottom edge. A proportional location of .5 sets the
divider at the center.
// Create a left-right split pane
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, rightComponent);
// Get current location; result is number of pixels from the left
edge
int loc = [Link]();
// Set a new location using an absolution location; center the
divider
loc = (int)(([Link]().getWidth()-[Link]())/2);
[Link](loc);
double propLoc = .5D;
// Set a proportional location
[Link](propLoc);
98. Setting the Size of the Divider in a JSplitPane Container
A divider can be no less than one pixel in size.
// Create a left-right split pane
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
leftComponent, rightComponent);
// Get current size; it is look and feel dependent
int size = [Link]();
// Set a new size
size = 1;
[Link](size);
JTABBEDPANE
99. Creating a JTabbedPane Container
A tabbed pane is a container that displays only one child component at a time. Typically,
the children are themselves containers of other components. Each child is associated with
a visible tab on the tabbed pane. The user can choose a child to display by selecting the
tab associated with that child.
// Create a child container which is to be associated with a tab
JPanel panel = new JPanel();
// Add components to the panel...
// Specify on which edge the tabs should appear
int location = [Link]; // or BOTTOM, LEFT, RIGHT
// Create the tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add a tab
String label = "Tab Label";
[Link](label, panel);
100. Getting and Setting the Selected Tab in a JTabbedPane Container
// Get the index of the currently selected tab
int selIndex = [Link]();
// Select the last tab
selIndex = [Link]()-1;
[Link](selIndex
101. Adding a Tab to a JTabbedPane Container
This example demonstrates various ways to add a tab to a tabbed pane.
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add a tab with a label taken from the name of the component
[Link]("Tab Label");
[Link](component1);
// Add a tab with a label at the end of all tabs
String label = "Tab Label";
[Link](label, component2);
// Add a tab with a label and icon at the end of all tabs
Icon icon = new ImageIcon("[Link]");
[Link](label, icon, component3);
// Add a tab with a label, icon, and tool tip at the end of all tabs
String tooltip = "Tool Tip Text";
[Link](label, icon, component4, tooltip);
// Insert a tab after the first tab
int index = 1;
[Link](label, icon, component5, tooltip, index);
102. Removing a Tab in a JTabbedPane Container
// Remove the last tab
[Link]([Link]()-1);
// Remove the tab with the specified child component
[Link](component);
// Remove all the tabs
[Link]();
103. Moving a Tab in a JTabbedPane Container
To move a tab, it must first be removed and then reinserted into the tabbed pane as a new
tab. Unfortunately, since there is no object that represents a tab, it is necessary to record
all of the tab's properties before moving it and to restore them after the new tab has been
created.
This example moves the last tab to the first position:
int src = [Link]()-1;
int dst = 0;
// Get all the properties
Component comp = [Link](src);
String label = [Link](src);
Icon icon = [Link](src);
Icon iconDis = [Link](src);
String tooltip = [Link](src);
boolean enabled = [Link](src);
int keycode = [Link](src);
int mnemonicLoc = [Link](src);
Color fg = [Link](src);
Color bg = [Link](src);
// Remove the tab
[Link](src);
// Add a new tab
[Link](label, icon, comp, tooltip, dst);
// Restore all properties
[Link](dst, iconDis);
[Link](dst, enabled);
[Link](dst, keycode);
[Link](dst, mnemonicLoc);
[Link](dst, fg);
[Link](dst, bg);
104. Getting the Tabs in a JTabbedPane Container
This example retrieves all the tabs in a tabbed pane:
// To create a tabbed pane
// Get number of tabs
int count = [Link]();
// Get the properties of each tab
for (int i=0; i<count; i++) {
// Get label
String label = [Link](i);
// Get icon
Icon icon = [Link](i);
// Get tool tip
String tooltip = [Link](i);
// Is enabled?
boolean enabled = [Link](i);
// Get mnemonic
int keycode = [Link](i);
// Get component associated with tab
Component comp = [Link](i);
}
Most of the methods that allow the properties of a tab to be changed require the index of
the tab. The index of a tab can change as tabs are added, removed, or moved. Here are
three ways to retrieve the index of a tab when needed.
// Get the index of the first tab that matches a label
String label = "Tab Label";
int index = [Link](label);
// Get the index of the first tab that matches an icon; the supplied
// icon must be the same instance that was used to create the tab
index = [Link](icon);
// Get the index of the tab by matching the child component; the
supplied
// component must be the same instance that was used to create the
tab
index = [Link](component);
if (index < 0) {
// The tab could not be found
}
105. Setting the Location of the Tabs in a JTabbedPane Container
The tabs of a tabbed pane can be placed on one of the four edges of its container. By
default, when a tabbed pane is created, the tabs are placed on top.
// Create a tabbed pane with the tabs on top
JTabbedPane pane = new JTabbedPane();
// Get current location
int loc = [Link](); // TOP
// Create a tabbed pane with tabs at a particular location
int location = [Link]; // or TOP, BOTTOM, RIGHT
pane = new JTabbedPane(location);
// Change the tab location
[Link]([Link]);
106. Enabling and Disabling a Tab in a JTabbedPane Container
By default, all new tabs are enabled, which means the user can select them. A tab can be
disabled to prevent the user from selecting it.
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add a tab
[Link]("Tab Label", component);
// Get index of the new tab
int index = [Link]()-1;
// Determine whether the tab is enabled
boolean enabled = [Link](index);
// Disable the tab
[Link](index, false);
107. Setting the Tool Tip for a Tab in a JTabbedPane Container
There are two ways to set a tool tip on a tab. The first is to specify it when the tab is
created; the second way is to set it using [Link]().
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add a tab with a tool tip
String label = "Tab Label";
String tooltip = "Tool Tip Text";
[Link](label, null, component, tooltip);
// Get index of new tab
int index = [Link]()-1;
// Get current tool tip
tooltip = [Link](index);
// Change tool tip
tooltip = "New Tool Tip Text";
[Link](index, tooltip);
108. Setting the Color of a Tab in a JTabbedPane Container
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Set the text color for all tabs
[Link]([Link]);
// Set the background color for all tabs
[Link]([Link]);
// Add a tab
String label = "Tab Label";
[Link](label, component);
// Get index of the new tab
int index = [Link]()-1;
// Set text color for the new tab
[Link](index, [Link]);
// Set background color for the new tab
[Link](index, [Link]);
109. Enabling the Selection of a Tab in a JTabbedPane Container Using a
Keystroke
Setting a mnemonic on a tab allows the tab to be selected with a keystroke. For example,
if the mnemonic for a tab were the key L, then typing ALT-L (on Windows) would select
the tab.
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add a tab
[Link]("Tab Label", component);
// Get index of the new tab
int index = [Link]()-1;
// Set the mnemonic; on some look and feels, the L in the label will
be underlined
int keycode = KeyEvent.VK_L;
[Link](index, keycode);
110. Enable Scrolling Tabs in a JTabbedPane Container
By default, all the tabs in a tabbed pane are displayed. When the tabs are wider than the
width of the tabbed pane, they are displayed in rows. If space is an issue, it is possible to
configure the tabs to appear in a single row along with a scroller that allows the tabs to be
scrolled into view.
// Create a tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add some tabs...; // Get the number of rows of tabs
int rows = [Link]();
// Get the current layout policy
int policy = [Link](); // WRAP_TAB_LAYOUT
// Configure the tabs to scroll
[Link](JTabbedPane.SCROLL_TAB_LAYOUT);
111. Determining When the Selected Tab Changes in a JTabbedPane
Container
A tabbed pane fires a change event whenever the selected tab is changed either by the
user or programmatically.
// Create the tabbed pane
JTabbedPane pane = new JTabbedPane();
// Add tabs...;
// Register a change listener
[Link](new ChangeListener() {
// This method is called whenever the selected tab changes
public void stateChanged(ChangeEvent evt) {
JTabbedPane pane = (JTabbedPane)[Link]();
// Get current tab
int sel = [Link]();
}
});
JDESKTOP AND INTERNALFRAME
112. Creating a JDesktopPane Container
A desktop is a container that can only hold internal frames (JInternalFrame objects).
This example creates a desktop with an internal frame.
// Create an internal frame
boolean resizable = true;
boolean closeable = true;
boolean maximizable = true;
boolean iconifiable = true;
String title = "Frame Title";
JInternalFrame iframe = new JInternalFrame(title, resizable,
closeable, maximizable, iconifiable);
// Set an initial size
int width = 200;
int height = 50;
[Link](width, height);
// By default, internal frames are not visible; make it visible
[Link](true);
// Add components to internal frame...
[Link]().add(new JTextArea());
// Add internal frame to desktop
JDesktopPane desktop = new JDesktopPane();
[Link](iframe);
// Display the desktop in a top-level frame
JFrame frame = new JFrame();
[Link]().add(desktop, [Link]);
[Link](300, 300);
[Link](true);
113. Getting All Frames in a JDesktopPane Container
// To create a desktop,
// Retrieve all internal frames
JInternalFrame[] frames = [Link]();
for (int i=0; i<[Link]; i++) {
// Get internal frame's title
String title = frames[i].getTitle();
// Determine if the internal frame is visible
boolean isVisible = frames[i].isVisible();
// Get other properties
boolean isCloseable = frames[i].isClosable();
boolean isResizeable = frames[i].isResizable();
boolean isIconifiable = frames[i].isIconifiable();
boolean isIcon = frames[i].isIcon();
boolean isMaximizable = frames[i].isMaximizable();
boolean isSelected = frames[i].isSelected();
}
TOOLTIPS
114. Setting a Tool Tip
If a JComponent such as a JButton is created using an action, the component will be
created with the tool tip text in the action ). However, if the action does not have any tool
tip text or if it must be changed, use [Link]() is used.
JComponent button = new JButton("Label");
// Set tool tip text
[Link]("tool tip text");
115. Setting the Location of a Tool Tip
By default, when a tool tip of a component appears, its northwest corner appears at the
same x-coordinate as the cursor and 20 pixels lower than the y-coordinate of the cursor.
To change this default location for a component, the getToolTipLocation() method of
the component must be overridden.
// Set the location of the tool tip such that its nw corner
// coincides with the nw corner of the button
JButton button = new JButton("My Button") {
public Point getToolTipLocation(MouseEvent event) {
return new Point(0, 0);
}
};
// Set the location of the tool tip such that its nw corner
// coincides with the bottom center of the button
button = new JButton("My Button") {
public Point getToolTipLocation(MouseEvent event) {
return new Point(getWidth()/2, getHeight());
}
};
// Use the default tool tip location
button = new JButton("My Button") {
public Point getToolTipLocation(MouseEvent event) {
return null;
}
};
// Set the tool tip text
[Link]("aString");
116. Enabling and Disabling Tool Tips
By default, tool tips are enabled for the entire application. So if a component has a tool
tip text, it will be displayed. To enable or disable tool tips for the entire application,
[Link]() is used. Note: Enabling or disabling the tool tip for a
particular component can be done only by adding or removing the tool tip text on the
component.
// Enable tool tips for the entire application
[Link]().setEnabled(true);
// Disable tool tips for the entire application
[Link]().setEnabled(false);
117. Making Tool Tips Appear Immediately
By default, when the cursor enters a component, there is a 750-millisecond delay before
the tool tip is displayed. This example demonstrates how to show the tool tip
immediately.
// Get current delay
int initialDelay =
[Link]().getInitialDelay();
// Show tool tips immediately
[Link]().setInitialDelay(0);
// Show tool tips after a second
initialDelay = 1000;
[Link]().setInitialDelay(initialDelay);
118. Making Tool Tips Remain Visible
By default, a tool tip stays visible for 4 seconds. This example demonstrates how to keep
the tool tip showing as long as the cursor is in the component.
// Get current delay
int dismissDelay =
[Link]().getDismissDelay();
// Keep the tool tip showing
dismissDelay = Integer.MAX_VALUE;
[Link]().setDismissDelay(dismissDelay);
119. Showing Multiple Lines in a Tool Tip
A tool tip can show simple HTML tags when surrounded by the tags <HTML> and
</HTML>. This example shows how to create multiple lines by using the <BR> tag. See the
[Link] class documentation for a list of supported tags.
// Show two lines in the tool tip
[Link]("<html>"+"This is a"+"<br>"+"tool
tip"+"</html>");
// By default, the lines are left justified. Center the lines.
[Link]("<html><center>"+"This is a"+"<br>"+"tool
tip"+"</center></html>");
// Italicize the second line
[Link]("<html>"+"This is a"+"<br><i>"+"tool
tip"+"</i></html>");
120. Showing an Image in a Tool Tip
A tool tip can show simple HTML tags when surrounded by the tags <HTML> and
</HTML). This example shows how to include an image in a tool tip by using the <IMG>
tag. See the [Link] class documentation for a list of other
supported tags.
String imageName = "file:[Link]";
[Link]("<html>Here is an image <img
src="+imageName+"></html>");
LAYOUT
121. Laying Out Components in a Row or Column
A horizontal box container arranges the components left-to-right in their preferred sizes.
The row of components are vertically centered.
// Create horizontal box container
Box box = new Box(BoxLayout.X_AXIS);
// Here is a another way to create a horizontal box container
box = [Link]();
// Add components
[Link](component1);
[Link](component2);
A vertical box container arranges the components top-to-bottom aligned in their preferred
sizes. The column of components are left-aligned.
// Create vertical box container
box = new Box(BoxLayout.Y_AXIS);
// Here is a another way to create a vertical box container
box = [Link]();
// Add components
[Link](component1);
[Link](component2);
123. Separating Components in a Row or Column
Box box = new Box(BoxLayout.X_AXIS);
// Glue spreads the components as far apart as possible.
[Link](component1);
[Link]([Link]());
[Link](component2);
// Strut spreads the components apart by a fixed distance.
int width = 10;
[Link]([Link](width));
[Link](component3);
124. Laying Out Components in a Flow (Left-to-Right, Top-to-Bottom)
int align = [Link]; // or LEFT, RIGHT
JPanel panel = new JPanel(new FlowLayout(align));
[Link](component1);
[Link](component2);
125. Laying Out Components in a Grid
When components are added to the container, they fill the grid left-to-right, top-to-
bottom.
int rows = 2;
int cols = 2;
JPanel panel = new JPanel(new GridLayout(rows, cols));
[Link](component1);
[Link](component2);
126. Laying Out Components Using Absolute Coordinates
JPanel panel = new JPanel(null);
[Link](x, y, w, h);
[Link](component);
ACTIONS
127. Creating an Action
An action is used by a Swing component to invoke a method. To create an action, the
actionPerformed() method must be overridden. The action is then attached to a
component such as a button or bound to a keystroke in a text component. When the
button is activated or the keystroke is pressed, the action's actionPerformed() method
is called. Actions can be attached to more than one component or keystroke.
Actions can also contain other optional information, such as a label, icon, or tool tip text.
When the action is attached to a component, the component may use this information if
present. For example, if the action has a label and icon, a button created using that action
will use that label and icon.
This example defines an action and creates a button using the action.
// Create an action object
public Action action = new AbstractAction("Action Name") {
// This is an instance initializer; it is executed just after
the
// constructor of the superclass is invoked
{
// The following values are completely optional
// Set tool tip text
putValue(Action.SHORT_DESCRIPTION, "Tool Tip Text");
// This text is not directly used by any Swing component;
// however, this text could be used in a help system
putValue(Action.LONG_DESCRIPTION, "Context-Sensitive Help
Text");
// Set an icon
Icon icon = new ImageIcon("[Link]");
putValue(Action.SMALL_ICON, icon);
// Set a mnemonic character. In most look and feels, this
causes the
// specified character to be underlined This indicates that
if the component
// using this action has the focus and In some look and
feels, this causes
// the specified character in the label to be underlined and
putValue(Action.MNEMONIC_KEY, new
Integer([Link].VK_A));
// Set an accelerator key; this value is used by menu items
putValue(Action.ACCELERATOR_KEY,
[Link]("control F2"));
}
// This method is called when the action is invoked
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
128. Listing the Actions in a Component
This example demonstrates how to list all the actions in a component.
ActionMap map = [Link]();
// List actions in the component
list(map, [Link]());
// List actions in the component and in all parent action maps
list(map, [Link]());
public static void list(ActionMap map, Object[] actionKeys) {
if (actionKeys == null) {
return;
}
for (int i=0; i<[Link]; i++) {
// Get the action bound to this action key
while ([Link](actionKeys[i]) == null) {
map = [Link]();
}
Action action = (Action)[Link](actionKeys[i]);
}
}
A text component not only has an action map with actions, it also has keymaps with
actions. Moreover, every keymap has a default action to handle any typed character key
events not handled by any input map or keymap. The following code retrieves actions
from these objects:
// List the actions in the keymaps
if (component instanceof JTextComponent) {
JTextComponent textComp = (JTextComponent)component;
Keymap keymap = [Link]();
while (keymap != null) {
// Get actions in the keymap
Action[] actions = [Link]();
for (int i=0; i<[Link]; i++) {
Action action = actions[i];
}
// Get the default action in the keymap
Action defaultAction = [Link]();
keymap = [Link]();
}
}
129. Enabling an Action
Actions can be bound to many different kinds of components. When an action is enabled
or disabled, components that are bound to that action may automatically alter its display
to match the enabled state of the action. This example creates three components: a button,
a text component, and a menu item - - all bound to the same action. When the action is
disabled, the button and menu item will appear disabled and the text component will not
be able to invoke the action.
JFrame frame = new JFrame();
// Button
JButton button = new JButton(action);
// Text Component
JTextField textfield = new JTextField();
[Link](JComponent.WHEN_FOCUSED).put(
[Link]("F2"), [Link]([Link]));
[Link]().put([Link]([Link]), action);
// Menu Item
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu Label");
[Link](new JMenuItem(action));
[Link](menu);
[Link](menuBar);
// The action
public Action action = new AbstractAction("Action Name") {
public void actionPerformed(ActionEvent evt) {
// Perform action
}
};
KEYSTROKES AND INPUTMAPS
130. Creating a KeyStroke and Binding It to an Action
This example creates a number of keystrokes and adds them to the input map of a
component. When a keystroke is added to an input map, an action name must be
supplied. This action is invoked when the keystroke is pressed while the component has
the focus.
// Create some keystrokes and bind them all to the same action
[Link]().put([Link]("F2"),
"actionName");
[Link]().put([Link]("control A"),
"actionName");
[Link]().put([Link]("shift F2"),
"actionName");
[Link]().put([Link]('('),
"actionName");
[Link]().put([Link]("button3 F"),
"actionName");
[Link]().put([Link]("typed x"),
"actionName");
[Link]().put([Link]("released
DELETE"), "actionName");
[Link]().put([Link]("shift UP"),
"actionName");
// Add the action to the component
[Link]().put("actionName",
new AbstractAction("actionName") {
public void actionPerformed(ActionEvent evt) {
process(evt);
}
}
);
131. Converting a KeyStroke to a String
The [Link]() method does not return a string that can be parsed by
[Link](). The method keyStroke2String() in this example returns
a string that is parseable by [Link](). However, there is one
keystroke that cannot be represented as a string that can be parsed back to a keystroke - -
a typed space character. In order to bind an action to a typed space character,
[Link](new Character(' '), 0) needs to be called.
public static String keyStroke2String(KeyStroke key) {
StringBuffer s = new StringBuffer(50);
int m = [Link]();
if ((m & (InputEvent.SHIFT_DOWN_MASK|InputEvent.SHIFT_MASK)) !=
0) {
[Link]("shift ");
}
if ((m & (InputEvent.CTRL_DOWN_MASK|InputEvent.CTRL_MASK)) != 0)
{
[Link]("ctrl ");
}
if ((m & (InputEvent.META_DOWN_MASK|InputEvent.META_MASK)) != 0)
{
[Link]("meta ");
}
if ((m & (InputEvent.ALT_DOWN_MASK|InputEvent.ALT_MASK)) != 0) {
[Link]("alt ");
}
if ((m & (InputEvent.BUTTON1_DOWN_MASK|InputEvent.BUTTON1_MASK))
!= 0) {
[Link]("button1 ");
}
if ((m & (InputEvent.BUTTON2_DOWN_MASK|InputEvent.BUTTON2_MASK))
!= 0) {
[Link]("button2 ");
}
if ((m & (InputEvent.BUTTON3_DOWN_MASK|InputEvent.BUTTON3_MASK))
!= 0) {
[Link]("button3 ");
}
switch ([Link]()) {
case KeyEvent.KEY_TYPED:
[Link]("typed ");
[Link]([Link]() + " ");
break;
case KeyEvent.KEY_PRESSED:
[Link]("pressed ");
[Link](getKeyText([Link]()) + " ");
break;
case KeyEvent.KEY_RELEASED:
[Link]("released ");
[Link](getKeyText([Link]()) + " ");
break;
default:
[Link]("unknown-event-type ");
break;
}
return [Link]();
}
public static String getKeyText(int keyCode) {
if (keyCode >= KeyEvent.VK_0 && keyCode <= KeyEvent.VK_9 ||
keyCode >= KeyEvent.VK_A && keyCode <= KeyEvent.VK_Z) {
return [Link]((char)keyCode);
}
switch(keyCode) {
case KeyEvent.VK_COMMA: return "COMMA";
case KeyEvent.VK_PERIOD: return "PERIOD";
case KeyEvent.VK_SLASH: return "SLASH";
case KeyEvent.VK_SEMICOLON: return "SEMICOLON";
case KeyEvent.VK_EQUALS: return "EQUALS";
case KeyEvent.VK_OPEN_BRACKET: return "OPEN_BRACKET";
case KeyEvent.VK_BACK_SLASH: return "BACK_SLASH";
case KeyEvent.VK_CLOSE_BRACKET: return "CLOSE_BRACKET";
case KeyEvent.VK_ENTER: return "ENTER";
case KeyEvent.VK_BACK_SPACE: return "BACK_SPACE";
case KeyEvent.VK_TAB: return "TAB";
case KeyEvent.VK_CANCEL: return "CANCEL";
case KeyEvent.VK_CLEAR: return "CLEAR";
case KeyEvent.VK_SHIFT: return "SHIFT";
case KeyEvent.VK_CONTROL: return "CONTROL";
case KeyEvent.VK_ALT: return "ALT";
case KeyEvent.VK_PAUSE: return "PAUSE";
case KeyEvent.VK_CAPS_LOCK: return "CAPS_LOCK";
case KeyEvent.VK_ESCAPE: return "ESCAPE";
case KeyEvent.VK_SPACE: return "SPACE";
case KeyEvent.VK_PAGE_UP: return "PAGE_UP";
case KeyEvent.VK_PAGE_DOWN: return "PAGE_DOWN";
case KeyEvent.VK_END: return "END";
case KeyEvent.VK_HOME: return "HOME";
case KeyEvent.VK_LEFT: return "LEFT";
case KeyEvent.VK_UP: return "UP";
case KeyEvent.VK_RIGHT: return "RIGHT";
case KeyEvent.VK_DOWN: return "DOWN";
// numpad numeric keys handled below
case KeyEvent.VK_MULTIPLY: return "MULTIPLY";
case KeyEvent.VK_ADD: return "ADD";
case KeyEvent.VK_SEPARATOR: return "SEPARATOR";
case KeyEvent.VK_SUBTRACT: return "SUBTRACT";
case KeyEvent.VK_DECIMAL: return "DECIMAL";
case KeyEvent.VK_DIVIDE: return "DIVIDE";
case KeyEvent.VK_DELETE: return "DELETE";
case KeyEvent.VK_NUM_LOCK: return "NUM_LOCK";
case KeyEvent.VK_SCROLL_LOCK: return "SCROLL_LOCK";
case KeyEvent.VK_F1: return "F1";
case KeyEvent.VK_F2: return "F2";
case KeyEvent.VK_F3: return "F3";
case KeyEvent.VK_F4: return "F4";
case KeyEvent.VK_F5: return "F5";
case KeyEvent.VK_F6: return "F6";
case KeyEvent.VK_F7: return "F7";
case KeyEvent.VK_F8: return "F8";
case KeyEvent.VK_F9: return "F9";
case KeyEvent.VK_F10: return "F10";
case KeyEvent.VK_F11: return "F11";
case KeyEvent.VK_F12: return "F12";
case KeyEvent.VK_F13: return "F13";
case KeyEvent.VK_F14: return "F14";
case KeyEvent.VK_F15: return "F15";
case KeyEvent.VK_F16: return "F16";
case KeyEvent.VK_F17: return "F17";
case KeyEvent.VK_F18: return "F18";
case KeyEvent.VK_F19: return "F19";
case KeyEvent.VK_F20: return "F20";
case KeyEvent.VK_F21: return "F21";
case KeyEvent.VK_F22: return "F22";
case KeyEvent.VK_F23: return "F23";
case KeyEvent.VK_F24: return "F24";
case KeyEvent.VK_PRINTSCREEN: return "PRINTSCREEN";
case KeyEvent.VK_INSERT: return "INSERT";
case KeyEvent.VK_HELP: return "HELP";
case KeyEvent.VK_META: return "META";
case KeyEvent.VK_BACK_QUOTE: return "BACK_QUOTE";
case KeyEvent.VK_QUOTE: return "QUOTE";
case KeyEvent.VK_KP_UP: return "KP_UP";
case KeyEvent.VK_KP_DOWN: return "KP_DOWN";
case KeyEvent.VK_KP_LEFT: return "KP_LEFT";
case KeyEvent.VK_KP_RIGHT: return "KP_RIGHT";
case KeyEvent.VK_DEAD_GRAVE: return "DEAD_GRAVE";
case KeyEvent.VK_DEAD_ACUTE: return "DEAD_ACUTE";
case KeyEvent.VK_DEAD_CIRCUMFLEX: return "DEAD_CIRCUMFLEX";
case KeyEvent.VK_DEAD_TILDE: return "DEAD_TILDE";
case KeyEvent.VK_DEAD_MACRON: return "DEAD_MACRON";
case KeyEvent.VK_DEAD_BREVE: return "DEAD_BREVE";
case KeyEvent.VK_DEAD_ABOVEDOT: return "DEAD_ABOVEDOT";
case KeyEvent.VK_DEAD_DIAERESIS: return "DEAD_DIAERESIS";
case KeyEvent.VK_DEAD_ABOVERING: return "DEAD_ABOVERING";
case KeyEvent.VK_DEAD_DOUBLEACUTE: return "DEAD_DOUBLEACUTE";
case KeyEvent.VK_DEAD_CARON: return "DEAD_CARON";
case KeyEvent.VK_DEAD_CEDILLA: return "DEAD_CEDILLA";
case KeyEvent.VK_DEAD_OGONEK: return "DEAD_OGONEK";
case KeyEvent.VK_DEAD_IOTA: return "DEAD_IOTA";
case KeyEvent.VK_DEAD_VOICED_SOUND: return
"DEAD_VOICED_SOUND";
case KeyEvent.VK_DEAD_SEMIVOICED_SOUND: return
"DEAD_SEMIVOICED_SOUND";
case KeyEvent.VK_AMPERSAND: return "AMPERSAND";
case KeyEvent.VK_ASTERISK: return "ASTERISK";
case KeyEvent.VK_QUOTEDBL: return "QUOTEDBL";
case KeyEvent.VK_LESS: return "LESS";
case KeyEvent.VK_GREATER: return "GREATER";
case KeyEvent.VK_BRACELEFT: return "BRACELEFT";
case KeyEvent.VK_BRACERIGHT: return "BRACERIGHT";
case KeyEvent.VK_AT: return "AT";
case KeyEvent.VK_COLON: return "COLON";
case KeyEvent.VK_CIRCUMFLEX: return "CIRCUMFLEX";
case KeyEvent.VK_DOLLAR: return "DOLLAR";
case KeyEvent.VK_EURO_SIGN: return "EURO_SIGN";
case KeyEvent.VK_EXCLAMATION_MARK: return "EXCLAMATION_MARK";
case KeyEvent.VK_INVERTED_EXCLAMATION_MARK:
return "INVERTED_EXCLAMATION_MARK";
case KeyEvent.VK_LEFT_PARENTHESIS: return "LEFT_PARENTHESIS";
case KeyEvent.VK_NUMBER_SIGN: return "NUMBER_SIGN";
case KeyEvent.VK_MINUS: return "MINUS";
case KeyEvent.VK_PLUS: return "PLUS";
case KeyEvent.VK_RIGHT_PARENTHESIS: return
"RIGHT_PARENTHESIS";
case KeyEvent.VK_UNDERSCORE: return "UNDERSCORE";
case KeyEvent.VK_FINAL: return "FINAL";
case KeyEvent.VK_CONVERT: return "CONVERT";
case KeyEvent.VK_NONCONVERT: return "NONCONVERT";
case KeyEvent.VK_ACCEPT: return "ACCEPT";
case KeyEvent.VK_MODECHANGE: return "MODECHANGE";
case KeyEvent.VK_KANA: return "KANA";
case KeyEvent.VK_KANJI: return "KANJI";
case KeyEvent.VK_ALPHANUMERIC: return "ALPHANUMERIC";
case KeyEvent.VK_KATAKANA: return "KATAKANA";
case KeyEvent.VK_HIRAGANA: return "HIRAGANA";
case KeyEvent.VK_FULL_WIDTH: return "FULL_WIDTH";
case KeyEvent.VK_HALF_WIDTH: return "HALF_WIDTH";
case KeyEvent.VK_ROMAN_CHARACTERS: return "ROMAN_CHARACTERS";
case KeyEvent.VK_ALL_CANDIDATES: return "ALL_CANDIDATES";
case KeyEvent.VK_PREVIOUS_CANDIDATE: return
"PREVIOUS_CANDIDATE";
case KeyEvent.VK_CODE_INPUT: return "CODE_INPUT";
case KeyEvent.VK_JAPANESE_KATAKANA: return
"JAPANESE_KATAKANA";
case KeyEvent.VK_JAPANESE_HIRAGANA: return
"JAPANESE_HIRAGANA";
case KeyEvent.VK_JAPANESE_ROMAN: return "JAPANESE_ROMAN";
case KeyEvent.VK_KANA_LOCK: return "KANA_LOCK";
case KeyEvent.VK_INPUT_METHOD_ON_OFF: return
"INPUT_METHOD_ON_OFF";
case KeyEvent.VK_AGAIN: return "AGAIN";
case KeyEvent.VK_UNDO: return "UNDO";
case KeyEvent.VK_COPY: return "COPY";
case KeyEvent.VK_PASTE: return "PASTE";
case KeyEvent.VK_CUT: return "CUT";
case KeyEvent.VK_FIND: return "FIND";
case KeyEvent.VK_PROPS: return "PROPS";
case KeyEvent.VK_STOP: return "STOP";
case KeyEvent.VK_COMPOSE: return "COMPOSE";
case KeyEvent.VK_ALT_GRAPH: return "ALT_GRAPH";
}
if (keyCode >= KeyEvent.VK_NUMPAD0 && keyCode <=
KeyEvent.VK_NUMPAD9) {
char c = (char)(keyCode - KeyEvent.VK_NUMPAD0 + '0');
return "NUMPAD"+c;
}
return "unknown(0x" + [Link](keyCode, 16) + ")";
}
132. Listing the Key Bindings in a Component
This example demonstrates how to list all the key bindings in a component. Text
components have an additional set of key bindings called a keymap.
// List keystrokes in the WHEN_FOCUSED input map of the component
InputMap map = [Link](JComponent.WHEN_FOCUSED);
list(map, [Link]());
// List keystrokes in the component and in all parent input maps
list(map, [Link]());
// List keystrokes in the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT input
map of the component
map =
[Link](JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
list(map, [Link]());
// List keystrokes in all related input maps
list(map, [Link]());
// List keystrokes in the WHEN_IN_FOCUSED_WINDOW input map of the
component
map = [Link](JComponent.WHEN_IN_FOCUSED_WINDOW);
list(map, [Link]());
// List keystrokes in all related input maps
list(map, [Link]());
public static void list(InputMap map, KeyStroke[] keys) {
if (keys == null) {
return;
}
for (int i=0; i<[Link]; i++) {
// This method is defined in Converting a KeyStroke to a
String
String keystrokeStr = keyStroke2String(keys[i]);
// Get the action name bound to this keystroke
while ([Link](keys[i]) == null) {
map = [Link]();
}
if ([Link](keys[i]) instanceof String) {
String actionName = (String)[Link](keys[i]);
} else {
Action action = (Action)[Link](keys[i]);
}
}
}
133. Sharing an InputMap or an ActionMap Between Two Components
By sharing an InputMap or ActionMap, any change to the shared InputMap or
ActionMap will affect all components sharing the InputMap or ActionMap.
WHEN_FOCUSED and WHEN_ANCESTOR_OF_FOCUSED_COMPONENT types of InputMaps can be
shared. WHEN_IN_FOCUSED_WINDOW InputMaps cannot be shared.
// Get an InputMap from the desired type of component and initialize
it
InputMap im = new JTextArea().getInputMap(JComponent.WHEN_FOCUSED);
[Link]([Link]("F2"), "actionName");
// Get an ActionMap from the desired type of component and
initialize it
ActionMap am = new JTextArea().getActionMap();
[Link]("actionName",
new AbstractAction("actionName") {
public void actionPerformed(ActionEvent evt) {
process((JTextComponent)[Link]());
}
}
);
// Use the shared InputMap and ActionMap
[Link](JComponent.WHEN_FOCUSED, im);
[Link](JComponent.WHEN_FOCUSED, im);
[Link](am);
[Link](am);
// Now, any change to the shared InputMap or ActionMap will affect
both component1 and component2
[Link]([Link]("F3"), "actionName2");
[Link]("actionName2",
new AbstractAction("actionName2") {
public void actionPerformed(ActionEvent evt) {
process((JTextComponent)[Link]());
}
}
);
134. Finding a Key Binding in a Component
This example searches all of a component's inputmaps and keymaps (if the component is
a text component) for a particular keystroke.
FindResult r = find([Link]("ctrl pressed C"),
component);
r = find([Link]("ctrl released C"), component);
r = find([Link]("C"), component);
r = find([Link]("typed C"), component);
r = find([Link](new Character('\u0002'), 0),
component);
// The results of a find are returned in a FindResult object
static class FindResult {
// Non-null if the keystroke is in an inputmap
InputMap inputMap;
// Non-null if the keystroke is in an keymap or default action
Keymap keymap;
// Non-null if the keystroke is in a default action
// The keymap field holds the keymap containing the default
action
Action defaultAction;
// If true, the keystroke is in the component's inputMap or
keymap
// and not in one of the inputMap's or keymap's parent.
boolean isLocal;
public String toString() {
StringBuffer b = new StringBuffer();
[Link]("inputmap="+inputMap+",keymap="+keymap
+",defaultAction="+defaultAction+",isLocal="+isLocal);
return [Link]();
}
}
// Returns null if not found
public static FindResult find(KeyStroke k, JComponent c) {
FindResult result;
result = find(k, [Link](JComponent.WHEN_FOCUSED));
if (result != null) {
return result;
}
result = find(k,
[Link](JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
if (result != null) {
return result;
}
result = find(k,
[Link](JComponent.WHEN_IN_FOCUSED_WINDOW));
if (result != null) {
return result;
}
// Check keymaps
if (c instanceof JTextComponent) {
JTextComponent tc = (JTextComponent)c;
result = new FindResult();
// Check local keymap
Keymap kmap = [Link]();
if ([Link](k)) {
[Link] = kmap;
[Link] = true;
return result;
}
// Check parent keymaps
kmap = [Link]();
while (kmap != null) {
if ([Link](k)) {
[Link] = kmap;
return result;
}
kmap = [Link]();
}
// Look for default action
if ([Link]() == KeyEvent.KEY_TYPED) {
// Check local keymap
kmap = [Link]();
if ([Link]() != null) {
[Link] = kmap;
[Link] = [Link]();
[Link] = true;
return result;
}
// Check parent keymaps
kmap = [Link]();
while (kmap != null) {
if ([Link]() != null) {
[Link] = kmap;
[Link] = [Link]();
return result;
}
kmap = [Link]();
}
}
}
return null;
}
public static FindResult find(KeyStroke k, InputMap map) {
// Check local inputmap
KeyStroke[] keys = [Link]();
for (int i=0; keys != null && i<[Link]; i++) {
if ([Link](keys[i])) {
FindResult result = new FindResult();
[Link] = map;
[Link] = true;
return result;
}
}
// Check parent inputmap
map = [Link]();
while (map != null) {
keys = [Link]();
for (int i=0; keys != null && i<[Link]; i++) {
if ([Link](keys[i])) {
FindResult result = new FindResult();
[Link] = map;
return result;
}
}
map = [Link]();
}
return null;
}
135. Adding an InputMap to a Component
InputMap inputMap = new InputMap();
// Add a KeyStroke
[Link]([Link]("F2"), "actionName");
[Link]([Link](JComponent.WHEN_FOCUSED));
[Link](JComponent.WHEN_FOCUSED, inputMap);
THESCREEN
136. Capturing a Screen Shot
try {
Robot robot = new Robot();
// Capture a particular area on the screen
int x = 100;
int y = 100;
int width = 200;
int height = 200;
Rectangle area = new Rectangle(x, y, width, height);
BufferedImage bufferedImage = [Link](area);
// Capture the whole screen
area = new
Rectangle([Link]().getScreenSize());
bufferedImage = [Link](area);
} catch (AWTException e) {
}
137. Converting Between Component and Screen Coordinates
This example demonstrates how to convert a coordinate within a component to a
coordinate on the screen and visa versa.
// Convert a coordinate relative to a component's bounds to screen
coordinates
Point pt = new Point([Link]());
[Link](pt, component);
// Convert a coordinate on a screen to a coordinate relative to a
component's bounds
[Link](pt, component);
LOOK AND FEEL
138. Determining the Available Look and Feels
[Link][] info =
[Link]();
for (int i=0; i<[Link]; i++) {
// Get the name of the look and feel that is suitable for
display to the user
String humanReadableName = info[i].getName();
String className = info[i].getClassName();
// The className is used with [Link]()
139. Getting and Setting a Look and Feel
To change the look and feel, you need to know the class name of the new look and feel.
This example installs the Windows look and feel.
// Get the currently installed look and feel
LookAndFeel lf = [Link]();
// Install a different look and feel; specifically, the Windows look
and feel
try {
[Link]("[Link]
dFeel");
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
} catch (UnsupportedLookAndFeelException e) {
} catch (IllegalAccessException e) {
}
140. Getting and Setting a Native Look and Feel
By default, Swing uses a cross-platform look and feel called Metal. In most cases, it is
more desirable to use a look and feel that is closer to the platform on which the
application is being run. This example demonstrates how to retrieve and install the look
and feel that most closely resembles the current platform.
// Get the native look and feel class name
String nativeLF = [Link]();
// Install the look and feel
try {
[Link](nativeLF);
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
} catch (UnsupportedLookAndFeelException e) {
} catch (IllegalAccessException e) {
}
It is also possible to retrieve the cross-platform look and feel:
String javaLF = [Link]();
141. Setting the Default Look and Feel Using a System Property or
Property File
By default, Swing uses a cross-platform look and feel called Metal. This default can be
changed with a system property on the command line, an entry in a properties file, or
programmatically.
The following example demonstrates how to set the look and feel using a system property
on the command line:
> java
-[Link]=[Link]
MyApp
Alternatively, the default look and feel can be set in a properties file called
`[Link]' located in the `<JAVAHOME>/lib' directory. The name of the
property is [Link].
# Specify the default look and feel
[Link]=[Link]
UI DEFAULT VALUES
142. Getting the Default Values for a Look and Feel
This example demonstrates how to retrieve all the default values for the current look and
feel.
// Get the currently installed look and feel
UIDefaults uidefs = [Link]();
// Retrieve the keys. Can't use an iterator since the map
// may be modified during the iteration. So retrieve all at once.
String[] keys = (String[])[Link]().toArray(new String[0]);
for (int i=0; i<[Link]; i++) {
Object v = [Link](keys[i]);
if (v instanceof Integer) {
int intVal = [Link](keys[i]);
} else if (v instanceof Boolean) {
boolean boolVal = [Link](keys[i]);
} else if (v instanceof String) {
String strVal = [Link](keys[i]);
} else if (v instanceof Dimension) {
Dimension dimVal = [Link](keys[i]);
} else if (v instanceof Insets) {
Insets insetsVal = [Link](keys[i]);
} else if (v instanceof Color) {
Color colorVal = [Link](keys[i]);
} else if (v instanceof Font) {
Font fontVal = [Link](keys[i]);
} else if (v instanceof Border) {
Border borderVal = [Link](keys[i]);
} else if (v instanceof Icon) {
Icon iconVal = [Link](keys[i]);
} else if (v instanceof
[Link][]) {
[Link][] keyBindsVal =
([Link][])[Link](keys[i]);
} else if (v instanceof InputMap) {
InputMap imapVal = (InputMap)[Link](keys[i]);
} else {
// Unknown type
}
}
145. Setting a UI Default Value That Is Created When Fetched
When a UI default value is fairly large and may never be used, the value should be lazily
created. This means that the value should be created only when the value is fetched. The
UIDefaults table allows for such values.
For values that are created every time they are fetched. This example declares a lazy
value (a JPanel) that is created only when fetched.
// Create a lazy value
Object lazyValue = new [Link]() {
// This method is called once, when the value is fetched.
// If this method can be called no more than once, it must be
synchronized.
public Object createValue(UIDefaults table) {
// The returned value will be permanently stored in the UI
default table
return new JPanel();
}
};
// Add the lazy value to the UI defaults table
[Link]("key", lazyValue);
// Fetch the value; this causes the value to be created
Object value = [Link]("key");
146. Setting a UI Default Value That Is Created at Every Fetch
The UIDefaults table supports values that are created every time they are fetched. Such
values are called active values.
This example declares an active value (a Date) that is created every time it is fetched.
// Create an active value
Object activeValue = new [Link]() {
// This method is called every time the value is fetched.
// If this method can be called no more than once, it must be
synchronized.
public Object createValue(UIDefaults table) {
return new Date();
}
};
// Add the active value to the UI defaults table
[Link]("key", activeValue);
// Fetch the value twice; this causes the value to be created twice
Date d1 = (Date)[Link]("key");
Date d2 = (Date)[Link]("key");
boolean b = [Link](d2); // false
[Link]
147. Creating and Setting a Border
There are several types of borders available, each represented by its own class. A border
can be created using the class' constructor or using a border factory. The border factory is
the typical method for creating a border since it creates the border using values that are
compatible with the current look and feel. However, if custom values are required, the
border should be created using a constructor.
// Create a border
EmptyBorder emptyBorder =
(EmptyBorder)[Link]();
LineBorder lineBorder =
(LineBorder)[Link]([Link]);
EtchedBorder etchedBorder =
(EtchedBorder)[Link]();
BevelBorder raisedBevelBorder =
(BevelBorder)[Link]();
BevelBorder loweredBevelBorder =
(BevelBorder)[Link]();
ImageIcon icon = new ImageIcon("[Link]");
MatteBorder matteBorder =
(MatteBorder)[Link](-1, -1, -1, -1, icon);
// Set the border
[Link](emptyBorder);
148. Adding a Title to a Border
// Use default border
TitledBorder titledBorder =
[Link]("Title");
// Create the title around existing border
titledBorder = [Link](border, "Title");
// Also available: DEFAULT_JUSTIFICATION, LEFT, RIGHT
[Link]([Link]);
// Also available: DEFAULT_POSITION, ABOVE_TOP, TOP,
// ABOVE_BOTTOM, BOTTOM, BELOW_BOTTOM
[Link](TitledBorder.BELOW_TOP);
[Link](titledBorder);
149. Creating a Compound Border
// border1 is around border2
Border newBorder = [Link](border1,
border2);
[Link](newBorder);
[Link]
150. Creating a JColorChooser Dialog
The following example creates a temporary color chooser dialog and shows it:
Color initialColor = [Link];
// Show the dialog; this method does not return until the dialog is
closed
Color newColor = [Link](frame, "Dialog Title",
initialColor);
Here is a more elaborate example that defines an action that creates and shows a color
chooser dialog. This action can be used in components such as a button or a menu item.
// This action creates and shows a modeless color chooser dialog.
public class ShowColorChooserAction extends AbstractAction {
JColorChooser chooser;
JDialog dialog;
ShowColorChooserAction(JFrame frame, JColorChooser chooser) {
super("Color Chooser...");
[Link] = chooser;
// Choose whether dialog is modal or modeless
boolean modal = false;
// Create the dialog that contains the chooser
dialog = [Link](frame, "Dialog Title",
modal,
chooser, null, null);
}
public void actionPerformed(ActionEvent evt) {
// Show dialog
[Link](true);
// Disable the action; to enable the action when the dialog
is closed, see
setEnabled(false);
}
};
Here's some code that demonstrates the use of the action:
JFrame frame = new JFrame();
// Create a color chooser dialog
Color initialColor = [Link];
JColorChooser chooser = new JColorChooser(initialColor);
// Create a button using the action
JButton button = new JButton(new ShowColorChooserAction(frame,
chooser));
151. Getting and Setting the Selected Color in a JColorChooser Dialog
Normally, the color is retrieved from a color chooser dialog when the dialog is closed.
// Create the chooser
JColorChooser chooser = new JColorChooser();
// Set the selected color
[Link]([Link]);
// Create and show dialog.
// Get current selected color
Color color = [Link]();
PREVIEW PANEL
152. Customizing the Preview Panel of a JColorChooser Dialog
The preview panel shows the selected color in a particular context. The default preview
panel colors some text with the selected color.
It may be desirable to change the preview panel to a more relevant setting. For example,
if the color chooser is used to color an image, a miniature version of the image can be
shown in the preview panel.
JColorChooser chooser = new JColorChooser();
[Link](new MyPreviewPanel(chooser));
// This preview panel simply displays the currently selected color.
public class MyPreviewPanel extends JComponent {
// The currently selected color
Color curColor;
public MyPreviewPanel(JColorChooser chooser) {
// Initialize the currently selected color
curColor = [Link]();
// Add listener on model to detect changes to selected color
ColorSelectionModel model = [Link]();
[Link](new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
ColorSelectionModel model =
(ColorSelectionModel)[Link]();
// Get the new color value
curColor = [Link]();
}
}) ;
// Set a preferred size
setPreferredSize(new Dimension(50, 50));
}
// Paint current color
public void paint(Graphics g) {
[Link](curColor);
[Link](0, 0, getWidth()-1, getHeight()-1);
}
}
153. Removing the Preview Panel from a JColorChooser Dialog
The preview panel can be removed by setting a do-nothing component.
JColorChooser chooser = new JColorChooser();
[Link](new JPanel());
// This preview panel simply displays the currently selected color.
public class MyPreviewPanel extends JComponent {
// The currently selected color
Color curColor;
public MyPreviewPanel(JColorChooser chooser) {
// Initialize the currently selected color
curColor = [Link]();
// Add listener on model to detect changes to selected color
ColorSelectionModel model = [Link]();
[Link](new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
ColorSelectionModel model =
(ColorSelectionModel)[Link]();
// Get the new color value
curColor = [Link]();
}
}) ;
// Set a preferred size
setPreferredSize(new Dimension(50, 50));
}
// Paint current color
public void paint(Graphics g) {
[Link](curColor);
[Link](0, 0, getWidth()-1, getHeight()-1);
}
}
COLORCHOOSERPANEL
154. Retrieving the Color Chooser Panels in a JColorChooser Dialog
There are three chooser panels in the default JColorChooser dialog. Although each is
implemented by a class in the [Link] package, these classes are
not public. This example demonstrates how to identify these panels by class name.
JColorChooser chooser = new JColorChooser();
// Retrieve the swatch chooser
findPanel(chooser,
"[Link]");
// Retrieve the HSB chooser
findPanel(chooser,
"[Link]");
// Retrieve the RGB chooser
findPanel(chooser,
"[Link]");
// Returns the panel instance with the specified name.
// Returns null if not found.
public AbstractColorChooserPanel findPanel(JColorChooser chooser,
String name) {
AbstractColorChooserPanel[] panels = [Link]();
for (int i=0; i<[Link]; i++) {
String clsName = panels[i].getClass().getName();
if ([Link](name)) {
return panels[i];
}
}
return null;
}
155. Removing a Color Chooser Panel from a JColorChooser Dialog
Removing chooser panels is simply a matter of removeChooserPanel(). The issue is to
identify the panels that are to be kept. There are three chooser panels in the default
JColorChooser dialog. Although each is implemented by a class in the
[Link] package, these classes are not public. This example
demonstrates how to identify these panels by class name.
JColorChooser chooser = new JColorChooser();
// Retrieve the current set of panels
AbstractColorChooserPanel[] oldPanels = [Link]();
// Remove panels
for (int i=0; i<[Link]; i++) {
String clsName = oldPanels[i].getClass().getName();
if
([Link]("[Link]")) {
// Remove swatch chooser if desired
[Link](oldPanels[i]);
} else if
([Link]("[Link]")) {
// Remove rgb chooser if desired
[Link](oldPanels[i]);
} else if
([Link]("[Link]")) {
// Remove hsb chooser if desired
[Link](oldPanels[i]);
}
}
// This preview pane simply displays the currently selected color.
public class MyPreviewPane extends JComponent {
// The currently selected color
Color curColor;
public MyPreviewPane(JColorChooser chooser) {
// Initialize the currently selected color
curColor = [Link]();
// Add listener on model to detect changes to selected color
ColorSelectionModel model = [Link]();
[Link](new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
ColorSelectionModel model =
(ColorSelectionModel)[Link]();
// Get the new color value
curColor = [Link]();
}
}) ;
// Set a preferred size
setPreferredSize(new Dimension(50, 50));
}
// Paint current color
public void paint(Graphics g) {
[Link](curColor);
[Link](0, 0, getWidth()-1, getHeight()-1);
}
}
156. Setting the Order of the Color Chooser Panel Tabs in a
JColorChooser Dialog
The default order of chooser panels is: swatch chooser, HSB chooser, and RGB chooser.
This example demonstrates how to change the ordering.
JColorChooser chooser = new JColorChooser();
// Retrieve the number of panels
int numPanels = [Link]().length;
// Create an array with the desired order of panels
// findPanel() is defined in
AbstractColorChooserPanel[] newPanels = new
AbstractColorChooserPanel[numPanels];
newPanels[0] = findPanel(chooser,
"[Link]");
newPanels[1] = findPanel(chooser,
"[Link]");
newPanels[2] = findPanel(chooser,
"[Link]");
// Set the new order of panels
[Link](newPanels);
157 . Adding a Custom Color Chooser Panel to a JColorChooser Dialog
This example creates a color chooser panel with three colored buttons. Clicking on a
button changes the selected color to the color of the button.
JColorChooser chooser = new JColorChooser();
[Link](new MyChooserPanel());
public class MyChooserPanel extends AbstractColorChooserPanel {
// These are the methods that must be implemented
// in order to create a color chooser panel.
// This is called once to initialize the panel.
public void buildChooser() {
setLayout(new GridLayout(0, 3));
makeAddButton("Red", [Link]);
makeAddButton("Green", [Link]);
makeAddButton("Blue", [Link]);
}
// This method is called whenever the user chooses this panel.
// This method should retrieve the currently selected color.
public void updateChooser() {
}
// This method is called to retrieve the label used
// in the tab that selects this panel.
public String getDisplayName() {
return "MyChooserPanel";
}
// This method is currently not used.
public Icon getSmallDisplayIcon() {
return null;
}
// This method is currently not used.
public Icon getLargeDisplayIcon() {
return null;
}
// These are helper methods specifically for this example
// Creates a color button and adds it to this panel.
private void makeAddButton(String name, Color color) {
JButton button = new JButton(name);
[Link](color);
[Link](setColorAction);
add(button);
}
// This action takes the background color of the button
// and uses it to set the selected color.
Action setColorAction = new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
JButton button = (JButton)[Link]();
getColorSelectionModel().setSelectedColor([Link]());
}
};
}
EVENTS
159. Listening for OK and Cancel Events in a JColorChooser Dialog
This example defines an action that creates and shows a color chooser dialog.
// Create the chooser
final JColorChooser chooser = new JColorChooser();
// Define listener for ok events
ActionListener okListener = new ActionListener() {
// Called when user clicks ok
public void actionPerformed(ActionEvent evt) {
// Note: The source is an internal button in the dialog
// and should not be used
// Get selected color
Color newColor = [Link]();
}
};
// Define listener for cancel events
ActionListener cancelListener = new ActionListener() {
// Called when user clicks cancel
public void actionPerformed(ActionEvent evt) {
// Note: The source is an internal button in the dialog
// and should not be used
// Note: The original color is not restored.
// getColor() returns the latest selected color.
Color newColor = [Link]();
}
};
// Choose whether dialog is modal or modeless
boolean modal = false;
// Create the dialog that contains the chooser
dialog = [Link](null, "Dialog Title", modal,
chooser, okListener, cancelListener);
// Add listener for clicks to the close-window icon
[Link](new WindowAdapter() {
// Called when user clicks the close-window icon.
// This type of event is usually treated like a cancel.
public void windowClosing(WindowEvent evt) {
// Note: The original color is not restored.
// getColor() returns the latest selected color.
Color newColor = [Link]();
}
}) ;
160. Listening for Changes to the Selected Color in a JColorChooser
Dialog
JColorChooser chooser = new JColorChooser();
ColorSelectionModel model = [Link]();
// Add listener on model to detect changes to selected color
[Link](new ChangeListener() {
public void stateChanged(ChangeEvent evt) {
ColorSelectionModel model =
(ColorSelectionModel)[Link]();
// Get the new color value
Color newColor = [Link]();
}
}) ;
[Link]
161. Listening for Hyperlink Events from a JEditorPane Component
Hyperlink events are fired by a JEditorPane when the user clicks on a hyperlink.
try {
String url = "[Link]
JEditorPane editorPane = new JEditorPane(url);
[Link](false);
[Link](new MyHyperlinkListener());
} catch (IOException e) {
}
class MyHyperlinkListener implements HyperlinkListener {
public void hyperlinkUpdate(HyperlinkEvent evt) {
if ([Link]() ==
[Link]) {
JEditorPane pane = (JEditorPane)[Link]();
try {
// Show the new page in the editor pane.
[Link]([Link]());
} catch (IOException e) {
}
}
}
}