The Checkbox Component Checkbox is a fairly simple component that defines one item that can be either Checkbox class has constructors that allow you to specify its label, its state true
Trang 1l3.setForeground(Color.red);
l3.setBackground(Color.black);
l3.setFont(new Font(“Courier”, Font.PLAIN, 16));
List l4 = new List();
l4.add(“Not Enabled”);
l4.add(“Nope”);
l4.select(1);
l4.setEnabled(false);
//Make the Frame and add the Lists to it ComponentTestFrame frame = new ComponentTestFrame(“List Test”);
frame.add(l1);
frame.add(l2);
frame.add(l3);
frame.add(l4);
frame.setVisible(true);
} public static void main(String args[]) { ListTest lt = new ListTest();
} }
198
J a
s o
l ut
n e
FIGURE 6.9
TheList
component allows the users to choose only one, or more than one, item, depending on how you set it up
The Checkbox Component
Checkbox is a fairly simple component that defines one item that can be either
Checkbox class has constructors that allow you to specify its label, its state ( true
or false ), and the CheckboxGroup it belongs to Table 6.10 shows some of the Checkbox class’s methods.
The CheckboxTest application creates some Checkbox objects Figure 6.10 shows the output You can select or deselect any one of these objects except for the two disabled ones (Garlic and Sugar) Note that you can also select more than one of
true to false , or from false to true
Trang 2i n
i n
/*
* CheckboxTest
* Demonstrates the Checkbox Component
*/
import java.awt.*;
public class CheckboxTest { public CheckboxTest() { //Make the Checkboxes Checkbox cb1 = new Checkbox(“Peppers”);
Checkbox cb2 = new Checkbox(“Onions”);
Method Description
the given Stringlabel
Checkbox(String, boolean) Constructs a new Checkboxwith the given
Stringlabel and the given state (trueif it
is initially checked, or falseif it is not)
Checkbox(String, boolean, CheckboxGroup) Constructs a new Checkboxwith the given
Stringlabel and the given state (trueif it
is initially checked, or falseif it is not) It
is specified as a member of the given
CheckboxGroup.
Checkbox(String, CheckboxGroup, boolean) Constructs a new Checkboxwith the given
Stringlabel and the given state (trueif it
is initially checked, or falseif it is not) It
is specified as a member of the given
CheckboxGroup.
addItemListener(ItemListener) Adds the given ItemListener
CheckboxGroup getCheckboxGroup() Returns this Checkbox’s CheckboxGroupor
nullif it is not part of a CheckboxGroup
Checkbox
checked
removeItemListener(ItemListener) Removes the specified ItemListener
setCheckboxGroup(CheckboxGroup) Sets this Checkbox’s CheckboxGroup
TA B L E 6 1 0 CH E C K B O X ME T H O D S
Trang 3Checkbox cb3 = new Checkbox(“Celery”);
Checkbox cb4 = new Checkbox(“Garlic”, true);
cb4.setEnabled(false);
Checkbox cb5 = new Checkbox(“Tomatoes”);
Checkbox cb6 = new Checkbox(“Salt”, true);
Checkbox cb7 = new Checkbox(“Pepper”, false);
Checkbox cb8 = new Checkbox();
cb8.setLabel(“Sugar”);
cb8.setState(false);
cb8.setEnabled(false);
//Make the Frame and add the Checkboxes to it ComponentTestFrame frame = new ComponentTestFrame(“Checkbox Test”);
frame.add(cb1);
frame.add(cb2);
frame.add(cb3);
frame.add(cb4);
frame.add(cb5);
frame.add(cb6);
frame.add(cb7);
frame.add(cb8);
frame.setVisible(true);
} public static void main(String args[]) { CheckboxTest cbt = new CheckboxTest();
} }
200
J a
s o
l ut
n e
FIGURE 6.10
TheseCheckbox
components are either checked or unchecked More than one box can
be checked at a time
Using the CheckboxGroup Class
The CheckboxGroup class is used to group Checkbox objects together in such a way that only one of them can be selected at any given time Simply specifying
CheckboxGroup group = new CheckboxGroup();
Checkbox cb1 = new Checkbox(“One”, true, group);
Checkbox cb2 = new Checkbox(“Two”, false, group);
Checkbox cb3 = new Checkbox(“Three”, false, group);
Trang 4This code creates three Checkbox es that are all part of the same CheckboxGroup Only one of them can be checked at any one time cb1 is initially checked because
of its second argument being true Checking any of the other two will cause cb1
to become unchecked The CheckboxGroup class defines methods used for setting and getting the selected Checkbox : Checkbox getSelectedCheckbox() , which returns the Checkbox in the group that is currently checked, and setSelected-Checkbox(Checkbox) , which checks the given Checkbox
Checkbox es in a CheckboxGroupare also sometimes called radio buttons.
The CheckboxGroupTest application adds all its Checkbox es to the same Checkbox-Group When you run it, notice that only one of them can be checked at any given time The output is shown in Figure 6.11 Here is a listing of the source code:
/*
* CheckboxGroupTest
* Demonstrates the CheckboxGroup Class
*/
import java.awt.*;
public class CheckboxGroupTest { public CheckboxGroupTest() { //Make the CheckboxGroup CheckboxGroup cbg = new CheckboxGroup();
Checkbox cb1 = new Checkbox(“Red”, false, cbg);
Checkbox cb2 = new Checkbox(“Green”, false, cbg);
Checkbox cb3 = new Checkbox(“Blue”, false, cbg);
Checkbox cb4 = new Checkbox(“Yellow”, true, cbg);
cb4.setEnabled(false);
Checkbox cb5 = new Checkbox(“Orange”, false, cbg);
Checkbox cb6 = new Checkbox(“Purple”, false, cbg);
Checkbox cb7 = new Checkbox(“Cyan”, false, cbg);
Checkbox cb8 = new Checkbox(“Magenta”, false, cbg);
//Make the Frame and add the Checkboxes to it ComponentTestFrame frame = new ComponentTestFrame(“CheckboxGroup Test”);
frame.add(cb1);
frame.add(cb2);
frame.add(cb3);
frame.add(cb4);
frame.add(cb5);
frame.add(cb6);
frame.add(cb7);
frame.add(cb8);
frame.setVisible(true);
}
H I N T
201
i n
i n
Trang 5public static void main(String args[]) { CheckboxGroupTest cbgt = new CheckboxGroupTest();
} }
202
J a
s o
l ut
n e
FIGURE 6.11
The
CheckboxGroup
class groups
Checkbox
components together so that only one can be checked at a time
The Canvas Component
A Canvas is a blank rectangular area primarily used for displaying graphics or for
the Component class, so all other components have it too It is responsible for ren-dering the component’s graphics and drawing them on-screen Although this is not covered in detail until the next chapter, I included a bit of it here because the Canvas component is not very useful without displaying some kind of graphical representation Remember your first applet way back in Chapter 1? You used the drawString(String, int, int) method there too This program simply creates the Canvas es, changes their colors, and displays them in the frame Canvases are typically used in GUI interfaces to display an image, or some other graphic, such
as a corporate logo, within a frame The output is shown in Figure 6.12 Here is the source code:
/*
* CanvasTest
* Demonstrates the Canvas Component
*/
import java.awt.*;
public class CanvasTest extends Canvas { public static void main(String args[]) { //Make the Canvas
CanvasTest c1 = new CanvasTest();
c1.setSize(100, 100);
Trang 6CanvasTest c2 = new CanvasTest();
c2.setSize(100, 100);
c2.setBackground(Color.orange);
c2.setForeground(Color.blue);
CanvasTest c3 = new CanvasTest();
c3.setSize(200, 50);
c3.setBackground(Color.white);
c3.setForeground(Color.lightGray);
CanvasTest c4 = new CanvasTest();
c4.setSize(80, 150);
c4.setBackground(Color.darkGray);
c4.setForeground(Color.white);
//Make the Frame and add the Canvas ComponentTestFrame frame = new ComponentTestFrame(“Canvas Test”);
frame.add(c1);
frame.add(c2);
frame.add(c3);
frame.add(c4);
frame.setVisible(true);
} /* Override the paint() method to alter its graphics */
public void paint(Graphics g) { g.setFont(new Font(“Arial”, Font.ITALIC + Font.BOLD, 16));
g.drawString(“Canvas”, 15, 25);
} }
203
i n
i n
The Menu Component
MenuBar Menu s drop down from the MenuBar when they are selected and contain
FIGURE 6.12
ACanvasis a component that can display graphics by overriding the
paint()method
Trang 7MenuItem s A MenuItem is an option that exists within a Menu Some of the more common MenuItem methods are summarized in Table 6.11 To use MenuItem s, you must first create them, add them to Menu s, then add the Menu s to the MenuBar , and then finally associate the MenuBar with the Frame Here’s a quick example:
MenuItem myItem = new MenuItem(“Some Option”);
Menu myMenu = new Menu(“Some Menu Title”);
myMenu.add(myItem);
MenuBar myBar = new MenuBar();
myBar.add(myMenu);
frame.setMenuBar(myMenuBar);
This assumes that frame is a valid Frame object Shortcut keys are also supported You can assign a shortcut key to a MenuItem , so that instead of clicking the menu bar and selecting the menu and finally the MenuItem , you can use a keyboard shortcut This is set either in the MenuItem(String, MenuShortcut) constructor
or the setShortcut(MenuShortcut) method The MenuShortcut class defines which key or key combo is the shortcut You specify this combo using KeyEvent
constants The MenuTest application sets some shortcuts just to demonstrate how it’s done.
204
J a
s o
l ut
n e
Method Description
given label
MenuItem(String, MenuShortcut) Constructs a new MenuItemobject with the
given label and MenuShortcut
addActionListener(ActionListener) Adds the specified ActionListenerto this
MenuItem
MenuShortcut getShortcut() Returns this MenuItem’s MenuShortcut boolean isEnabled() Returns whether this MenuItemis enabled
removeActionListener(ActionListener) Removes this MenuItem’s ActionListener
setEnabled(boolean) Sets whether this MenuItemis enabled
setLabel(String) Sets this MenuItemobject’s label to the
specifiedString.
setShortcut(MenuShortcut) Sets this MenuItem’s shortcut to the specified
MenuShortcut
TA B L E 6 1 1 ME N UIT E M ME T H O D S
Trang 8The MenuTest application builds two Menu s for the MenuBar and sets the MenuBar
for the Frame Here is the source:
/*
* MenuTest
* Demonstrates the MenuBar, Menu, and MenuItem classes
*/
import java.awt.*;
import java.awt.event.KeyEvent;
public class MenuTest { public MenuTest() { //create MenuBar object MenuBar menuBar = new MenuBar();
//create a Menu object Menu fileMenu = new Menu(“File”);
//create MenuItem objects MenuItem fm_new = new MenuItem(“New”);
fm_new.setShortcut(new MenuShortcut(KeyEvent.VK_N));
MenuItem fm_open = new MenuItem(“Open”);
fm_open.setShortcut(new MenuShortcut(KeyEvent.VK_O));
MenuItem fm_save = new MenuItem(“Save”);
fm_save.setShortcut(new MenuShortcut(KeyEvent.VK_S));
fm_save.setEnabled(false);
MenuItem fm_saveAs = new MenuItem(“Save As ”);
fm_saveAs.setShortcut(new MenuShortcut(KeyEvent.VK_A));
fm_saveAs.setEnabled(false);
MenuItem fm_exit = new MenuItem(“Exit”);
//add the MenuItems to the Menu with a Separator fileMenu.add(fm_new);
fileMenu.add(fm_open);
fileMenu.add(fm_save);
fileMenu.add(fm_saveAs);
//separator fileMenu.addSeparator();
fileMenu.add(fm_exit);
//make another quick Menu Menu editMenu = new Menu(“Edit”);
MenuItem em_options = new MenuItem(“Options”);
editMenu.add(em_options);
//add the Menus to the MenuBar menuBar.add(fileMenu);
menuBar.add(editMenu);
//create the Frame and add the MenuBar ComponentTestFrame frame = new ComponentTestFrame(“Menu Test”);
205
i n
i n
Trang 9frame.setBackground(Color.white);
frame.setVisible(true);
} public static void main(String args[]) { MenuTest mt = new MenuTest();
} }
It demonstrates how creating a bunch of MenuItem s and dumping them into the
Menu s then adding the Menu s to the MenuBar does this Here is an explanation for the more complicated parts The fm_new MenuItem adds a shortcut:
fm_new.setShortcut(new MenuShortcut(KeyEvent.VK_N));
Basically, the KeyEvent.VK_N constant specifies the N key on your keyboard You can see in the output in Figure 6.13 that this shortcut is indicated right next to the MenuItem ’s label It is Ctrl+N, although it might vary for different operating systems Menu s can also have separator lines that are used to separate different groups of MenuItem s (for cosmetic sake) You do this by calling the addSeparator()
method in the Menu class Here’s an example from MenuTest.java
fileMenu.addSeparator();
This line of code added a separator in the File menu, right in between the Save As… and Exit options Some of the MenuItem s were disabled You can see the dif-ference in their appearance.
Although it is not shown here, you can nest Menu s Menu is a subclass of MenuItem , so it is a MenuItem itself and can be added to other Menu s Try it out and see for yourself!
T R I C K
206
J a
s o
l ut
n e
FIGURE 6.13
TheMenuclass allows users to select options from
aFrame’s MenuBar
Trang 10The PopupMenu Component
The PopupMenu component is a subclass of Menu that doesn’t have to be attached
to a MenuBar It can pop up anywhere you specify it to by indicating a Component
and an x and y position relative to that Component ’s coordinate space You can attach a PopupMenu to a MenuBar or another Menu , but if you do, you can’t show it
at any old location that you choose because it is attached to something else A
PopupMenu is created similar to other Menu s It becomes visible by calling its
show(Component, int, int) method The specified Component ’s coordinate space
is used as a reference and the top-left corner of the PopupMenu is set to the loca-tion specified by the second and third arguments (x, y) The PopupMenuTest appli-cation demonstrates these concepts The output is shown in Figure 6.14 When you run it, the PopupMenu is initially shown, if you click anywhere at all, though,
it will simply disappear This example demonstrates the basics of creating a
pop-up menu In the real world, you would cause the pop-pop-up menu to become visible based on some event, such as right-clicking the frame Also, you should associate actions that are triggered when the user selects a menu item Text editors might use a pop-up menu that offers the Clipboard options (cut, copy, paste) Here is a listing of the source code for the PopupMenuTest.java example.
/*
* PopupMenuTest
* Demonstrates the PopupMenu Component
*/
import java.awt.*;
public class PopupMenuTest { public PopupMenuTest() { //create the PopupMenu PopupMenu popMenu = new PopupMenu(“Clipboard”);
//create the MenuItems MenuItem pm_cut = new MenuItem(“Cut”);
MenuItem pm_copy = new MenuItem(“Copy”);
MenuItem pm_paste = new MenuItem(“Paste”);
MenuItem pm_delete = new MenuItem(“Delete”);
//add the MenuItems to the PopupMenu popMenu.add(pm_cut);
popMenu.add(pm_copy);
popMenu.add(pm_paste);
popMenu.add(pm_delete);
//create the Frame and make show the PopupMenu ComponentTestFrame frame = new ComponentTestFrame(“PopupMenu Test”);
frame.add(popMenu);
frame.setVisible(true);
popMenu.show(frame, 50, 50);
}
207
i n
i n
Trang 11public static void main(String args[]) { PopupMenuTest pmt = new PopupMenuTest();
} }
208
J a
s o
l ut
n e
FIGURE 6.14
APopupMenuis similar to a Menu
except it’s not attached to a
MenuBar
The Panel Component
The Panel class is a simple extension of Container It can contain other
add components to it like this:
Panel myPanel = new Panel();
myPanel.add(someComponent);
The PanelTest application is a simple example of this It creates two Panel objects
each other, making it easier to determine their bounds Here is the source for PanelTest.java The output is shown in Figure 6.15.
/*
* PanelTest
* Demonstrates the Panel Component
*/
import java.awt.*;
public class PanelTest { public PanelTest() { //Create the Panels and add components to them Panel p1 = new Panel();
p1.setBackground(Color.red);
p1.add(new Label(“URL:”, Label.RIGHT));
p1.add(new TextField(25));
p1.add(new Button(“Go”));