Sie sind auf Seite 1von 25

How to Use Buttons, Check Boxes, and Radio Buttons

To create a button, you can instantiate one of the many classes that descend from
the AbstractButton class. The following table shows the Swing-
defined AbstractButton subclasses that you might want to use:

Class Summary Where Described


JButton A common button. How to Use the
Common Button
API and How to Use
JButton Features
JCheckBox A check box button. How to Use Check
Boxes
JRadioButton One of a group of radio buttons. How to Use Radio
Buttons
JMenuItem An item in a menu. How to Use Menus
JCheckBoxMenuItem A menu item that has a check box. How to Use
Menus and How to
Use Check Boxes
JRadioButtonMenuItem A menu item that has a radio button. How to Use
Menus and How to
Use Radio Buttons
JToggleButton Implements toggle functionality inherited Used in
by JCheckBox and JRadioButton. Can be some examples
instantiated or subclassed to create two-
state buttons.

Note: If you want to collect a group of buttons into a row or column, then you should check out tool bars.

First, this section explains the basic button API that AbstractButton defines and thus all Swing
buttons have in common. Next, it describes the small amount of API that JButton adds
to AbstractButton. After that, this section shows you how to use specialized API to implement check
boxes and radio buttons.

How to Use the Common Button API


Here is a picture of an application that displays three buttons:
Try this:

1. Click the Launch button to run the Button Demo using Java Web Start (download
JDK 7 or later). Alternatively, to compile and run the example yourself, consult

the example index.


2. Click the left button.
It disables the middle button (and itself, since it is no longer useful) and enables the
right button.
3. Click the right button.
It enables the middle button and the left button, and disables itself.

As the ButtonDemo example shows, a Swing button can display both text and an image.
In ButtonDemo, each button has its text in a different place, relative to its image. The underlined letter
in each button's text shows the mnemonic the keyboard alternative for each button. In most look
and feels, the user can click a button by pressing the Alt key and the mnemonic. For example, Alt-M
would click the Middle button in ButtonDemo.

When a button is disabled, the look and feel automatically generates the button's disabled appearance.
However, you could provide an image to be substituted for the normal image. For example, you could
provide gray versions of the images used in the left and right buttons.

How you implement event handling depends on the type of button you use and how you use it.
Generally, you implement an action listener, which is notified every time the user clicks the button.
For check boxes you usually use an item listener, which is notified when the check box is selected or
deselected.

Below is the code from ButtonDemo.java that creates the buttons in the previous example and reacts
to button clicks. The bold code is the code that would remain if the buttons had no images.

//In initialization code:


ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
ImageIcon middleButtonIcon = createImageIcon("images/middle.gif");
ImageIcon rightButtonIcon = createImageIcon("images/left.gif");

b1 = new JButton("Disable middle button", leftButtonIcon);


b1.setVerticalTextPosition(AbstractButton.CENTER);
b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for
left-to-right locales
b1.setMnemonic(KeyEvent.VK_D);
b1.setActionCommand("disable");

b2 = new JButton("Middle button", middleButtonIcon);


b2.setVerticalTextPosition(AbstractButton.BOTTOM);
b2.setHorizontalTextPosition(AbstractButton.CENTER);
b2.setMnemonic(KeyEvent.VK_M);

b3 = new JButton("Enable middle button", rightButtonIcon);


//Use the default text position of CENTER, TRAILING (RIGHT).
b3.setMnemonic(KeyEvent.VK_E);
b3.setActionCommand("enable");
b3.setEnabled(false);

//Listen for actions on buttons 1 and 3.


b1.addActionListener(this);
b3.addActionListener(this);

b1.setToolTipText("Click this button to disable "


+ "the middle button.");
b2.setToolTipText("This middle button does nothing "
+ "when you click it.");
b3.setToolTipText("Click this button to enable the "
+ "middle button.");
...
}

public void actionPerformed(ActionEvent e) {


if ("disable".equals(e.getActionCommand())) {
b2.setEnabled(false);
b1.setEnabled(false);
b3.setEnabled(true);
} else {
b2.setEnabled(true);
b1.setEnabled(true);
b3.setEnabled(false);
}
}

protected static ImageIcon createImageIcon(String path) {


java.net.URL imgURL = ButtonDemo.class.getResource(path);
...//error handling omitted for clarity...
return new ImageIcon(imgURL);
}

How to Use JButton Features

Ordinary buttons JButton objects have just a bit more functionality than
the AbstractButton class provides: You can make a JButton be the default button.

At most one button in a top-level container can be the default button. The default button typically has a
highlighted appearance and acts clicked whenever the top-level container has the keyboard focus and
the user presses the Return or Enter key. Here is a picture of a dialog, implemented in
the ListDialog example, in which the Set button is the default button:

You set the default button by invoking the setDefaultButton method on a top-level container's root
pane. Here is the code that sets up the default button for the ListDialog example:
//In the constructor for a JDialog subclass:
getRootPane().setDefaultButton(setButton);

The exact implementation of the default button feature depends on the look and feel. For example, in the
Windows look and feel, the default button changes to whichever button has the focus, so that pressing
Enter clicks the focused button. When no button has the focus, the button you originally specified as the
default button becomes the default button again.

How to Use Check Boxes

The JCheckBox class provides support for check box buttons. You can also put check boxes in menus,
using the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem inherit
from AbstractButton, Swing check boxes have all the usual button characteristics, as discussed
earlier in this section. For example, you can specify images to be used in check boxes.

Check boxes are similar to radio buttons but their selection model is different, by convention. Any
number of check boxes in a group none, some, or all can be selected. A group of radio buttons, on
the other hand, can have only one button selected.

Here is a picture of an application that uses four check boxes to customize a cartoon:

Try this:

1. Click the Launch button to run the CheckBox Demo using Java Web Start (download
JDK 7 or later). Alternatively, to compile and run the example yourself, consult

the example index.


2. Click the Chin button or press Alt-c.
The Chin check box becomes unselected, and the chin disappears from the picture.
The other check boxes remain selected. This application has one item listener that
listens to all the check boxes. Each time the item listener receives an event, the
application loads a new picture that reflects the current state of the check boxes.

A check box generates one item event and one action event per click. Usually, you listen only for item
events, since they let you determine whether the click selected or deselected the check box. Below is the
code from CheckBoxDemo.java that creates the check boxes in the previous example and reacts to
clicks.

//In initialization code:


chinButton = new JCheckBox("Chin");
chinButton.setMnemonic(KeyEvent.VK_C);
chinButton.setSelected(true);

glassesButton = new JCheckBox("Glasses");


glassesButton.setMnemonic(KeyEvent.VK_G);
glassesButton.setSelected(true);

hairButton = new JCheckBox("Hair");


hairButton.setMnemonic(KeyEvent.VK_H);
hairButton.setSelected(true);

teethButton = new JCheckBox("Teeth");


teethButton.setMnemonic(KeyEvent.VK_T);
teethButton.setSelected(true);

//Register a listener for the check boxes.


chinButton.addItemListener(this);
glassesButton.addItemListener(this);
hairButton.addItemListener(this);
teethButton.addItemListener(this);
...
public void itemStateChanged(ItemEvent e) {
...
Object source = e.getItemSelectable();

if (source == chinButton) {
//...make a note of it...
} else if (source == glassesButton) {
//...make a note of it...
} else if (source == hairButton) {
//...make a note of it...
} else if (source == teethButton) {
//...make a note of it...
}

if (e.getStateChange() == ItemEvent.DESELECTED)
//...make a note of it...
...
updatePicture();
}

How to Use Radio Buttons


Radio buttons are groups of buttons in which, by convention, only one button at a time can be selected.
The Swing release supports radio buttons with the JRadioButton andButtonGroup classes. To put
a radio button in a menu, use the JRadioButtonMenuItem class. Other ways of displaying one-of-
many choices are combo boxes and lists. Radio buttons look similar to check boxes, but, by convention,
check boxes place no limits on how many items can be selected at a time.

Because JRadioButton inherits from AbstractButton, Swing radio buttons have all the usual
button characteristics, as discussed earlier in this section. For example, you can specify the image
displayed in a radio button.

Here is a picture of an application that uses five radio buttons to let you choose which kind of pet is
displayed:
Try this:

1. Click the Launch button to run the RadioButton Demo using Java Web
Start (download JDK 7 or later). Alternatively, to compile and run the example yourself,

consult the example index.


2. Click the Dog button or press Alt-d.
The Dog button becomes selected, which makes the Bird button become unselected.
The picture switches from a bird to a dog. This application has one action listener that
listens to all the radio buttons. Each time the action listener receives an event, the
application displays the picture for the radio button that was just clicked.

Each time the user clicks a radio button (even if it was already selected), the button fires an action event.
One or two item events also occur one from the button that was just selected, and another from the
button that lost the selection (if any). Usually, you handle radio button clicks using an action listener.

Below is the code from RadioButtonDemo.java that creates the radio buttons in the previous
example and reacts to clicks.

//In initialization code:


//Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic(KeyEvent.VK_B);
birdButton.setActionCommand(birdString);
birdButton.setSelected(true);

JRadioButton catButton = new JRadioButton(catString);


catButton.setMnemonic(KeyEvent.VK_C);
catButton.setActionCommand(catString);

JRadioButton dogButton = new JRadioButton(dogString);


dogButton.setMnemonic(KeyEvent.VK_D);
dogButton.setActionCommand(dogString);

JRadioButton rabbitButton = new JRadioButton(rabbitString);


rabbitButton.setMnemonic(KeyEvent.VK_R);
rabbitButton.setActionCommand(rabbitString);

JRadioButton pigButton = new JRadioButton(pigString);


pigButton.setMnemonic(KeyEvent.VK_P);
pigButton.setActionCommand(pigString);

//Group the radio buttons.


ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);

//Register a listener for the radio buttons.


birdButton.addActionListener(this);
catButton.addActionListener(this);
dogButton.addActionListener(this);
rabbitButton.addActionListener(this);
pigButton.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
picture.setIcon(new ImageIcon("images/"
+ e.getActionCommand()
+ ".gif"));
}

For each group of radio buttons, you need to create a ButtonGroup instance and add each radio
button to it. The ButtonGroup takes care of unselecting the previously selected button when the user
selects another button in the group.

You should generally initialize a group of radio buttons so that one is selected. However, the API doesn't
enforce this rule a group of radio buttons can have no initial selection. Once the user has made a
selection, exactly one button is selected from then on.

The Button API


The following tables list the commonly used button-related API. Other methods you might call, such
as setFont and setForeground, are listed in the API tables in The JComponent Class.

The API for using buttons falls into these categories:

Setting or Getting the Button's Contents


Fine Tuning the Button's Appearance
Implementing the Button's Functionality
Check Box Constructors
Radio Button Constructors
Toggle Button Constructors
Commonly Used Button Group Constructors/Methods

Setting or Getting the Button's Contents


Method or Constructor Purpose
JButton(Action)
JButton(String, Icon) Create a JButton instance, initializing it to have the
JButton(String) specified text/image/action.
JButton(Icon)
JButton()
void setAction(Action) Set or get the button's properties according to values from
Action getAction() the Action instance.
Set or get the text displayed by the button. You can use
void setText(String)
HTML formatting, as described in Using HTML in Swing
String getText()
Components.
void setIcon(Icon) Set or get the image displayed by the button when the
Icon getIcon() button isn't selected or pressed.
Set or get the image displayed by the button when it is
void setDisabledIcon(Icon) disabled. If you do not specify a disabled image, then the
Icon getDisabledIcon() look and feel creates one by manipulating the default
image.
void setPressedIcon(Icon) Set or get the image displayed by the button when it is
Icon getPressedIcon() being pressed.
void setSelectedIcon(Icon)
Icon getSelectedIcon() Set or get the image displayed by the button when it is
void selected. If you do not specify a disabled selected image,
setDisabledSelectedIcon(Icon) then the look and feel creates one by manipulating the
Icon selected image.
getDisabledSelectedIcon()
setRolloverEnabled(boolean)
Use setRolloverIcon(someIcon) to make the button
boolean isRolloverEnabled()
display the specified icon when the cursor passes over it.
void setRolloverIcon(Icon)
The setRolloverSelectedIcon method lets you specify
Icon getRolloverIcon()
the rollover icon when the button is selected this is
void
useful for two-state buttons such as toggle buttons. Setting
setRolloverSelectedIcon(Icon)
the rollover icon automatically calls setRollover(true),
Icon
enabling rollover.
getRolloverSelectedIcon()
Fine Tuning the Button's Appearance
Method or Constructor Purpose
void Set or get where in the button its contents should be placed.
setHorizontalAlignment(int) The AbstractButton class allows any one of the following
void setVerticalAlignment(int) values for horizontal alignment: RIGHT, LEFT, CENTER (the
int getHorizontalAlignment() default), LEADING, and TRAILING. For vertical
int getVerticalAlignment() alignment: TOP, CENTER (the default), and BOTTOM.
void
Set or get where the button's text should be placed, relative
setHorizontalTextPosition(int)
to the button's image. The AbstractButton class allows
void
any one of the following values for horizontal
setVerticalTextPosition(int)
position: LEFT, CENTER, RIGHT, LEADING,
int
and TRAILING (the default). For vertical
getHorizontalTextPosition()
position: TOP, CENTER (the default), and BOTTOM.
int getVerticalTextPosition()
void setMargin(Insets) Set or get the number of pixels between the button's border
Insets getMargin() and its contents.
void setFocusPainted(boolean) Set or get whether the button should look different when it
boolean isFocusPainted() has the focus.
void
Set or get whether the border of the button should be
setBorderPainted(boolean)
painted.
boolean isBorderPainted()
void setIconTextGap(int) Set or get the amount of space between the text and the
int getIconTextGap() icon displayed in this button.
Implementing the Button's Functionality
Method or Constructor Purpose
Set or get the keyboard alternative to clicking the
button. One form of the setMnemonic method accepts
void setMnemonic(int)
a character argument; however, the Swing team
char getMnemonic()
recommends that you use an int argument instead,
specifying a KeyEvent.VK_X constant.
void Set or get a hint as to which character in the text
setDisplayedMnemonicIndex(int) should be decorated to represent the mnemonic. Note
int getDisplayedMnemonicIndex() that not all look and feels may support this.
void setActionCommand(String) Set or get the name of the action performed by the
String getActionCommand() button.
void
addActionListener(ActionListener) Add or remove an object that listens for action events
ActionListener fired by the button.
removeActionListener()
void addItemListener(ItemListener) Add or remove an object that listens for item events
ItemListener removeItemListener() fired by the button.
Set or get whether the button is selected. Makes sense
void setSelected(boolean)
only for buttons that have on/off state, such as check
boolean isSelected()
boxes.
Programmatically perform a "click". The optional
void doClick()
argument specifies the amount of time (in
void doClick(int)
milliseconds) that the button should look pressed.
void Set or get the amount of time (in milliseconds)
setMultiClickThreshhold(long) required between mouse press events for the button to
long getMultiClickThreshhold() generate corresponding action events.
Check Box Constructors
Constructor Purpose
JCheckBox(Action) Create a JCheckBox instance. The string argument
JCheckBox(String) specifies the text, if any, that the check box should display.
JCheckBox(String, boolean) Similarly, the Icon argument specifies the image that
JCheckBox(Icon) should be used instead of the look and feel's default check
JCheckBox(Icon, boolean) box image. Specifying the boolean argument
JCheckBox(String, Icon) as true initializes the check box to be selected. If the
JCheckBox(String, Icon, boolean argument is absent or false, then the check box
boolean) is initially unselected.
JCheckBox()
JCheckBoxMenuItem(Action)
JCheckBoxMenuItem(String)
JCheckBoxMenuItem(String,
boolean) Create a JCheckBoxMenuItem instance. The arguments are
JCheckBoxMenuItem(Icon) interpreted in the same way as the arguments to
JCheckBoxMenuItem(String, the JCheckBox constructors, except that any specified icon
Icon) is shown in addition to the normal check box icon.
JCheckBoxMenuItem(String,
Icon, boolean)
JCheckBoxMenuItem()
Radio Button Constructors
Constructor Purpose
JRadioButton(Action) Create a JRadioButton instance. The string argument
JRadioButton(String) specifies the text, if any, that the radio button should
JRadioButton(String, boolean) display. Similarly, the Icon argument specifies the image
JRadioButton(Icon) that should be used instead of the look and feel's default
JRadioButton(Icon, boolean) radio button image. Specifying the boolean argument
JRadioButton(String, Icon) as true initializes the radio button to be selected, subject
JRadioButton(String, Icon, to the approval of the ButtonGroup object. If the boolean
boolean) argument is absent or false, then the radio button is
JRadioButton() initially unselected.
JRadioButtonMenuItem(Action)
Create a JRadioButtonMenuItem instance. The
JRadioButtonMenuItem(String)
arguments are interpreted in the same way as the
JRadioButtonMenuItem(Icon)
arguments to the JRadioButton constructors, except that
JRadioButtonMenuItem(String,
any specified icon is shown in addition to the normal
Icon)
radio button icon.
JRadioButtonMenuItem()
Toggle Button Constructors
Constructor Purpose
JToggleButton(Action) Create a JToggleButton instance, which is similar to a JButton,
JToggleButton(String) but with two states. Normally, you use
JToggleButton(String, a JRadioButton or JCheckBox instead of directly
boolean) instantiating JToggleButton, but JToggleButton can be useful
JToggleButton(Icon) when you do not want the typical radio button or check box
JToggleButton(Icon, appearance. The string argument specifies the text, if any, that the
boolean) toggle button should display. Similarly, the Icon argument
JToggleButton(String, specifies the image that should be used. Specifying the boolean
Icon) argument as true initializes the toggle button to be selected. If
JToggleButton(String, the boolean argument is absent or false, then the toggle button is
Icon, boolean) initially unselected.
JToggleButton()
Commonly Used Button Group Constructors/Methods
Constructor or Method Purpose
ButtonGroup() Create a ButtonGroup instance.
void add(AbstractButton)
void Add a button to the group, or remove a button from the group.
remove(AbstractButton)
public ButtonGroup Get the ButtonGroup, if any, that controls a button. For
getGroup() example:
ButtonGroup group =
(in DefaultButtonModel) ((DefaultButtonModel)button.getModel()).getGroup();
public ButtonGroup Clears the state of selected buttons in the ButtonGroup. None
clearSelection() of the buttons in the ButtonGroup are selected .

Examples that Use Various Kinds of Buttons


The following examples use buttons. Also see Examples that Use Tool Bars, which lists programs that
add JButton objects to JToolBars.

Where
Example Notes
Described
How to Use the Uses mnemonics and icons. Specifies the button
ButtonDemo Common Button text position, relative to the button icon. Uses
API action commands.
Using HTML in
ButtonHtmlDemo
A version of ButtonDemo that uses HTML
Swing
formatting in its buttons.
Components
ListDialog
How to Use Implements a dialog with two buttons, one of
JButton Features which is the default button.
Has "Show it" buttons whose behavior is tied to
DialogDemo
How to Make the state of radio buttons. Uses sizable, though
Dialogs anonymous, inner classes to implement the action
listeners.
ProgressBarDemo
How to Monitor Implements a button's action listener with a named
Progress inner class.
CheckBoxDemo
How to Use Uses check box buttons to determine which of 16
Check Boxes images it should display.
ActionDemo
How to Use Uses check box menu items to set the state of the
Actions program.
RadioButtonDemo How to Use Uses radio buttons to determine which of five
Radio Buttons images it should display.
DialogDemo
How to Make Contains several sets of radio buttons, which it
Dialogs uses to determine which dialog to bring up.
MenuDemo
How to Use Contains radio button menu items and check box
Menus menu items.
ColorChooserDemo2
How to Use Color The crayons in CrayonPanel are implemented as
Choosers toggle buttons.
ScrollDemo
How to Use
The cm button is a toggle button.
Scroll Panes

You can learn more about JavaFX button components from the following documents:

Using JavaFX UI Controls: Button


Using JavaFX UI Controls: Radio Button
Using JavaFX UI Controls: Toggle Button
Using JavaFX UI Controls: Checkbox

Cmo utilizar los botones, casillas de verificacin y botones


de opcin
Para crear un botn, se puede crear una instancia de una de las muchas clases que descienden de
la AbstractButtonclase. La siguiente tabla muestra el columpio definidos por AbstractButtonlas
subclases que puede que desee utilizar:

Clase Resumen donde Descrito


JButton Un botn comn. Cmo utilizar la
API Botn
Comn y cmo
utilizar las
funciones JButton
JCheckBox Un botn de casilla de verificacin. Cmo utilizar los
cuadros de
marcacin
JRadioButton Pertenece a un grupo de botones de radio. Cmo utilizar
botones de opcin
JMenuItem Un elemento de un men. Cmo utilizar los
mens
JCheckBoxMenuItem Un elemento de men que tiene una casilla Cmo utilizar los
de verificacin. mens y cmo
utilizar los cuadros
de marcacin
JRadioButtonMenuItem Un elemento de men que tiene un botn de Cmo utilizar los
radio. mens y cmo
utilizar botones de
opcin
JToggleButton Implementa la funcionalidad de Se utiliza en
conmutacin heredado algunos ejemplos
por JCheckBoxy JRadioButton. Puede ser
una instancia o una subclase para crear
botones de dos estados.

Nota: Si desea recopilar un grupo de botones en una fila o columna, entonces usted debe comprobar
fuera de las barras de herramientas .

En primer lugar, esta seccin se explica la API botn bsico que AbstractButtondefine - y por lo
tanto todos los botones de Swing tienen en comn. A continuacin, se describe la pequea cantidad de
API que JButtonse suma a AbstractButton. Despus de eso, esta seccin se muestra cmo
utilizar la API especializado para implementar casillas de verificacin y botones de radio.

Cmo utilizar la API Botn Comn


Aqu est una imagen de una aplicacin que muestra tres botones:

Prueba esto:

1. Haga clic en el botn Iniciar para ejecutar la demostracin del botn usando Java
Web Start ( descarga de JDK 7 o posterior ). Alternativamente, para compilar y ejecutar

el ejemplo usted mismo, consultar el ndice de ejemplo .


2. Haga clic con el botn izquierdo.
Se desactiva el botn del medio (y s, puesto que ya no es til) y habilita el botn
derecho.
3. Haga clic en el botn derecho.
Permite que el botn central y el botn de la izquierda, y se desactiva.

A medida que el ButtonDemoejemplo muestra, un botn de oscilacin puede mostrar tanto texto como
una imagen. En ButtonDemo, cada botn tiene su texto en un lugar diferente, en relacin a su
imagen. La letra subrayada en el texto de cada botn muestra el mnemnico - la alternativa del teclado -
para cada botn. En la mayora look and feel, el usuario puede hacer clic en un botn pulsando la tecla
Alt y la tecla de acceso. Por ejemplo, Alt-M le haga clic en el botn central en ButtonDemo.

Cuando se desactiva un botn, la apariencia genera automticamente aspecto desactivado del


botn. Sin embargo, se podra proporcionar una imagen para ser sustituido por la imagen normal. Por
ejemplo, usted podra ofrecer versiones grises de las imgenes utilizadas en los botones izquierdo y
derecho.
Cmo se implementa el manejo de eventos depende del tipo de botn que utiliza y cmo lo usa. En
general, se implementa un oyente de action , que se notifica cada vez que el usuario hace clic en el
botn. Para casillas de verificacin que normalmente utiliza un receptor de elementos , que se notifica
cuando est seleccionada o no la casilla de verificacin.

A continuacin se muestra el cdigo del ButtonDemo.javaque crea los botones en el ejemplo


anterior y reacciona a los clics de botn. El cdigo en negrita es el cdigo que se mantendra si los
botones no tenan imgenes.

// En el cdigo de inicializacin:
ImageIcon leftButtonIcon = createImageIcon ( "imgenes / right.gif");
ImageIcon middleButtonIcon = createImageIcon ( "images /
middle.gif");
ImageIcon rightButtonIcon = createImageIcon ( "images / left.gif");
b1 = new JButton ( "botn Desactivar medio" , leftButtonIcon );
b1.setVerticalTextPosition (AbstractButton.CENTER);
b1.setHorizontalTextPosition (AbstractButton.LEADING); // aka
IZQUIERDA, para las configuraciones regionales de izquierda a derecha
b1.setMnemonic (KeyEvent.VK_D); b1.setActionCommand ( "desactivar"); b2 =
new JButton ( "Botn central" , middleButtonIcon );
b2.setVerticalTextPosition (AbstractButton.BOTTOM);
b2.setHorizontalTextPosition (AbstractButton.CENTER); b2.setMnemonic
(KeyEvent.VK_M); b3 = new JButton ( "botn central Activar" ,
rightButtonIcon );
// utilizar la posicin del texto por defecto de CENTRO, de salida
(derecha). b3.setMnemonic (KeyEvent.VK_E);
b3.setActionCommand ( "enable");
b3.setEnabled (false);
// detectar acciones en los botones 1 y 3. b1.addActionListener
(este);
b3.addActionListener (this);
b1.setToolTipText ( "Haga clic en este botn para desactivar"
+ "el botn central.");
b2.setToolTipText ( "Este botn central no hace nada"
+ "cuando se hace clic en l.");
b3.setToolTipText ( "Haga clic en este botn para activar el"
+ "botn central.");
...
} public void actionPerformed (ActionEvent e) {
si ( "desactivar" .equals (e.getActionCommand ())) {
b2.setEnabled (false);
b1.setEnabled (false);
b3.setEnabled (true);
} Else {
b2.setEnabled (true);
b1.setEnabled (true);
b3.setEnabled (false);
}
}
Protegido createImageIcon ImageIcon esttica (camino String) {
java.net.URL imgURL = ButtonDemo.class.getResource (ruta de acceso);
... // manejo de errores omite para mayor claridad ...
volver nueva ImageIcon (imgURL);
}
Cmo utilizar las funciones JButton

Botones ordinarias - JButtonObjetos - tienen funcionalidad slo un poco ms de


la AbstractButtonclase proporciona: Usted puede hacer una JButtonque sea el botn
predeterminado.

A lo sumo un botn en un contenedor de alto nivel puede ser el botn predeterminado. El botn
predeterminado tpicamente tiene una apariencia resaltada y los actos se hace clic cada vez que el
contenedor de nivel superior tiene el foco del teclado y el usuario presiona la tecla Intro. Aqu est una
foto de un cuadro de dilogo, implementado en el dilogo Lista de ejemplo, en el que el conjunto
de botn es el botn por defecto:

Se establece el botn predeterminado mediante la invocacin del setDefaultButtonmtodo de


panel raz de un contenedor de alto nivel. Aqu est el cdigo que configura el botn predeterminado
para el ListDialogejemplo:

// En el constructor de una subclase JDialog:


. GetRootPane () setDefaultButton (botn SET);

La aplicacin exacta de la funcin del botn predeterminado depende de la apariencia. Por ejemplo, en
el aspecto de Windows y sentir, el botn cambia por defecto a cualquier botn tiene el foco, para que al
pulsar Enter clic en el botn enfocada. Cuando hay un botn tiene el foco, el botn especificado
originalmente como el botn predeterminado se convierte en el botn predeterminado de nuevo.

Cmo utilizar los cuadros de marcacin


La JCheckBoxclase proporciona soporte para los botones de casilla de verificacin. Tambin se puede
poner casillas de verificacin de los mens , utilizando
laJCheckBoxMenuItemclase. Debido JCheckBoxy JCheckBoxMenuItemheredar
de AbstractButton, casillas de verificacin de Swing tienen todas las caractersticas habituales de
los botones, como se explic anteriormente en esta seccin. Por ejemplo, puede especificar las
imgenes que se utilizarn en las casillas de verificacin.

Las casillas de verificacin son similares a los botones de radio , pero su modelo de seleccin es
diferente, por convencin. Cualquier nmero de casillas de verificacin en un grupo - ninguno, algunos,
o todos - se pueden seleccionar. Un grupo de botones de radio, por el contrario, slo puede tener un
botn seleccionado.

Aqu est una imagen de una aplicacin que utiliza cuatro casillas de verificacin para personalizar un
dibujo animado:

Prueba esto:

1. Haga clic en el botn Iniciar para ejecutar la casilla de verificacin de demostracin


utilizando Java Web Start ( descarga de JDK 7 o posterior ). Alternativamente, para
compilar y ejecutar el ejemplo usted mismo, consultar el ndice de ejemplo .

2. Haga clic en la barbilla botn o presione Alt-c.


El Chin casilla de verificacin no seleccionada se convierte, y el mentn desaparece
de la imagen. Las dems casillas permanecen seleccionados. Esta aplicacin tiene un
oyente elemento que escucha todas las casillas de verificacin. Cada vez que el
receptor de elementos recibe un evento, la aplicacin carga una nueva imagen que
refleja el estado actual de las casillas de verificacin.

Una casilla de verificacin genera un evento elemento y un evento de accin por cada clic. Por lo
general, se escucha slo para eventos de elementos, ya que le permiten determinar si el clic
seleccionada o no en la casilla de verificacin. A continuacin se muestra el cdigo
de CheckBoxDemo.javaeso crea las casillas de verificacin en el ejemplo anterior y reacciona a los
clics.

// En el cdigo de inicializacin:
chinButton = new JCheckBox ( "Chin");
chinButton.setMnemonic (KeyEvent.VK_C);
chinButton.setSelected (true);

glassesButton = new JCheckBox ( "gafas");


glassesButton.setMnemonic (KeyEvent.VK_G);
glassesButton.setSelected (true);

hairButton = new JCheckBox ( "Hair");


hairButton.setMnemonic (KeyEvent.VK_H);
hairButton.setSelected (true);

teethButton = new JCheckBox ( "dientes");


teethButton.setMnemonic (KeyEvent.VK_T);
teethButton.setSelected (true);

// Se registra un oyente de las casillas de verificacin.


chinButton.addItemListener (this);
glassesButton.addItemListener (this);
hairButton.addItemListener (this);
teethButton.addItemListener (this);
...
public void itemStateChanged (ItemEvent e) {
...
fuente Object = e.getItemSelectable ();

si (fuente == chinButton) { //...make una nota de ella ...


} else if (fuente == glassesButton) { //...make una nota de ella ...
} else if (fuente = = hairButton) { //...make una nota de ella ...
} else if (fuente == teethButton) { //...make una nota de ella ...
}
si (e.getStateChange () == ItemEvent.DESELECTED) //...make una nota
de ella ...
...
updatePicture ();
}

Cmo utilizar botones de opcin

Los botones de radio son grupos de botones en la que, por convencin, slo un botn a la vez puede
ser seleccionado. La versin de Swing soporta botones de radio con
elJRadioButtony ButtonGroupclases. Para poner un botn de opcin en un men , utilice
la JRadioButtonMenuItemclase. Otras formas de mostrar uno-de-muchas opciones son cuadros
combinados y listas . Los botones de radio son similares a las casillas de verificacin , pero, por
convencin, casillas de verificacin no tienen lmites en el nmero de elementos se pueden seleccionar
a la vez.

Debido a que JRadioButtonhereda de AbstractButton, Swing botones de radio tienen todas las
caractersticas habituales de los botones, como se explic anteriormente en esta seccin. Por ejemplo,
puede especificar la imagen que aparece en un botn de radio.

Aqu est una imagen de una aplicacin que utiliza cinco botones de radio para que pueda elegir qu
tipo de mascota que se muestra:
Prueba esto:

1. Haga clic en el botn Iniciar para ejecutar el RadioButton demo usando Java Web
Start ( descarga de JDK 7 o posterior ). Alternativamente, para compilar y ejecutar el

ejemplo usted mismo, consultar el ndice de ejemplo .


2. Haga clic en el perro botn o presione Alt-d.
El perro botn queda seleccionado, lo que hace que el pjaro botn convertirse no
seleccionada. La imagen cambia de un ave a un perro. Esta aplicacin tiene un oyente
de action que escucha a todos los botones de radio. Cada vez que el oyente de action
recibe un evento, la aplicacin muestra la imagen para el botn de radio que se acaba
de hacer clic.

Cada vez que el usuario hace clic en un botn de radio (incluso si ya ha sido seleccionado), el botn
dispara un evento action . Uno o dos eventos artculo tambin se producen - uno desde el botn que se
acaba de seleccionar, y otra del botn que perdi la seleccin (si lo hay). Por lo general, usted maneja
clics de los botones de radio utilizando un oyente de action.

A continuacin se muestra el cdigo del RadioButtonDemo.javaque crea los botones de radio en el


ejemplo anterior y reacciona a los clics.

// En la inicializacin de cdigo:
// Crear los botones de radio.
JRadioButton birdButton = new JRadioButton (birdString);
birdButton.setMnemonic (KeyEvent.VK_B);
birdButton.setActionCommand (birdString);
birdButton.setSelected (true);

JRadioButton catButton = new JRadioButton (catString);


catButton.setMnemonic (KeyEvent.VK_C);
catButton.setActionCommand (catString);

JRadioButton dogButton = new JRadioButton (dogString);


dogButton.setMnemonic (KeyEvent.VK_D);
dogButton.setActionCommand (dogString);

JRadioButton rabbitButton = new JRadioButton (rabbitString);


rabbitButton.setMnemonic (KeyEvent.VK_R);
rabbitButton.setActionCommand (rabbitString);

JRadioButton pigButton = new JRadioButton (pigString);


pigButton.setMnemonic (KeyEvent.VK_P);
pigButton.setActionCommand (pigString);

// Grupo de los botones de radio.


Grupo ButtonGroup = new ButtonGroup ();
group.add (birdButton);
group.add (catButton);
group.add (dogButton);
group.add (rabbitButton);
group.add (pigButton);

// Se registra un oyente para los botones de radio.


birdButton.addActionListener (this);
catButton.addActionListener (this);
dogButton.addActionListener (this);
rabbitButton.addActionListener (this);
pigButton.addActionListener (this);
...
public void actionPerformed (ActionEvent e) {
picture.setIcon (nueva ImageIcon ( "images /"
+ e.getActionCommand ()
+ ".gif"));
}

Para cada grupo de botones de radio, es necesario crear una ButtonGroupinstancia y agregar cada
botn de radio a la misma. El ButtonGroupse encarga de deseleccionando el botn seleccionado
previamente cuando el usuario selecciona otro botn en el grupo.

En general, debera inicializar un grupo de botones de radio para que se seleccione esa. Sin embargo,
la API no cumplir esta regla - un grupo de botones de opcin no puede tener la seleccin inicial. Una vez
que el usuario ha realizado una seleccin, exactamente un botn se selecciona a partir de entonces.

El API Button

Las siguientes tablas muestran la API relacionada con botones de uso comn. Otros mtodos que se
podra llamar, como setFonty setForeground, se enumeran en las tablas API en la clase
JComponent .

El API para utilizar los botones se divide en estas categoras:

Seleccionar u Obtener Contenido del botn


Ajuste fino de aspecto del botn
La implementacin de la funcionalidad del botn
Casilla de verificacin de constructores
Constructores botn de opcin
Constructores botn de activacin
Comnmente botn usado Grupo de Constructores / Mtodos

Seleccionar u Obtener Contenido del botn


Mtodo o Constructor Propsito
JButton (Accin) Crear un JButtonejemplo, la inicializacin es tener el texto /
JButton (String, Icono) imagen / accin especificada.
JButton (String)
JButton (Icono)
JButton ()
setAction vaco (Accin) Selecciona u obtiene las propiedades del botn de acuerdo con
Accin getAction () los valores de la Actioninstancia.
Selecciona u obtiene el texto mostrado por el botn. Usted
setText vaco (cadena)
puede utilizar el formato HTML, como se describe en Uso de
Cadena getText ()
HTML en componentes de Swing .
setIcon vaco (Icono) Selecciona u obtiene la imagen mostrada por el botn cuando el
Icono getIcon () botn no est seleccionado o presionado.
Selecciona u obtiene la imagen mostrada por el botn cuando
setDisabledIcon vaco
est desactivada. Si no se especifica una imagen de personas con
(Icono)
discapacidad, a continuacin, el aspecto y el comportamiento
Icono getDisabledIcon ()
crea una manipulando la imagen predeterminada.
setPressedIcon vaco
Selecciona u obtiene la imagen mostrada por el botn cuando
(Icono)
est siendo presionado.
Icono getPressedIcon ()
setSelectedIcon vaco
(Icono)
Icono getSelectedIcon ()
Selecciona u obtiene la imagen mostrada por el botn cuando se
vaco
selecciona. Si no se especifica una imagen seleccionada
setDisabledSelectedIcon
desactivado, el aspecto y el comportamiento crea una
(Icono)
manipulando la imagen seleccionada.
Icono
getDisabledSelectedIcon
()
setRolloverEnabled
(boolean)
boolean
Utilizar setRolloverIcon(someIcon)para hacer que el botn
isRolloverEnabled ()
aparezca el icono especificado cuando el cursor pasa sobre
vaco setRolloverIcon
l. El setRolloverSelectedIconmtodo permite especificar el
(Icono)
icono de desplazamiento cuando se selecciona el botn - esto es
Icono getRolloverIcon ()
til para los botones de dos estados, tales como botones de
vaco
conmutacin. Ajuste del icono de desplazamiento de forma
setRolloverSelectedIcon
automtica las llamadas setRollover(true), lo que permite
(Icono)
vuelco.
Icono
getRolloverSelectedIcon
()
Ajuste fino de aspecto del botn
Mtodo o Constructor Propsito
setHorizontalAlignment Selecciona u obtiene dnde en el botn se deben colocar su
vaco (int) contenido. La AbstractButtonclase permite una cualquiera de
vaco los siguientes valores para la alineacin
setVerticalAlignment (int) horizontal: RIGHT, LEFT, CENTER(el valor
int predeterminado), LEADINGy TRAILING. Para la alineacin
getHorizontalAlignment () vertical: TOP, CENTER(el valor predeterminado), y BOTTOM.
int getVerticalAlignment ()
setHorizontalTextPosition
anular (int)
vaco Selecciona u obtiene en el texto del botn debe ser colocado,
setVerticalTextPosition en relacin con la imagen del botn. La AbstractButtonclase
(int) permite una cualquiera de los siguientes valores para la
int posicin horizontal: LEFT, CENTER, RIGHT, LEADING,
getHorizontalTextPosition y TRAILING(el valor predeterminado). Para la posicin
() vertical: TOP, CENTER(el valor predeterminado), y BOTTOM.
int getVerticalTextPosition
()
setMargin vaco
Selecciona u obtiene el nmero de pxeles entre el borde de
(recuadros)
Button y su contenido.
Insets getMargin ()
void setFocusPainted
Selecciona u obtiene si el botn debera ser diferente cuando se
(boolean)
tiene el foco.
boolean isFocusPainted ()
void setBorderPainted
(boolean) Selecciona u obtiene si el borde del botn debe ser pintado.
boolean isBorderPainted ()
setIconTextGap vaco
Selecciona u obtiene la cantidad de espacio entre el texto y el
(int)
icono que aparece en este botn.
int getIconTextGap ()
La implementacin de la funcionalidad del botn
Mtodo o Constructor Propsito
Selecciona u obtiene la alternativa teclado para hacer clic
en el botn. Una forma del setMnemonicmtodo acepta un
setMnemonic vaco (int)
argumento de carcter; Sin embargo, el equipo de
Char getMnemonic ()
oscilacin recomienda que utilice un intargumento en su
lugar, especificando una constante.KeyEvent.VK_X
setDisplayedMnemonicIndex
Selecciona u obtiene una pista sobre qu personaje en el
vaco (int)
texto debe ser decorado para representar la tecla de
int
acceso. Tenga en cuenta que no todo el look and feel puede
getDisplayedMnemonicIndex
apoyar esto.
()
setActionCommand vaco
Selecciona u obtiene el nombre de la accin realizada por
(cadena)
el botn.
Cadena getActionCommand ()
addActionListener vaco
(ActionListener) Aadir o eliminar un objeto que escucha los eventos de
ActionListener accin disparados por el botn.
removeActionListener ()
addItemListener vaco
(ItemListener) Aadir o eliminar un objeto que escucha los eventos de
ItemListener artculos disparados por el botn.
removeItemListener ()
Selecciona u obtiene si se selecciona el botn. Slo tiene
anular setSelected (boolean)
sentido para los botones que tienen estado activado /
boolean isSelected ()
desactivado, tales como casillas de verificacin.
Mediante programacin realizar un "clic". El argumento
doClick vaco ()
opcional especifica la cantidad de tiempo (en
vaco doClick (int)
milisegundos) que el botn debe verse presionado.
setMultiClickThreshhold vaco Selecciona u obtiene la cantidad de tiempo (en
(largo) milisegundos) necesaria entre eventos de prensa de ratn
de largo para el botn de generar eventos de accin
getMultiClickThreshhold () correspondientes.
Casilla de verificacin de constructores
Constructor Propsito
JCheckBox (Accin)
JCheckBox (String)
Crear una JCheckBoxinstancia. El argumento de cadena especifica
JCheckBox (String,
el texto, en su caso, de que la casilla de verificacin debe
boolean)
mostrar. Del mismo modo, el Iconargumento especifica la
JCheckBox (icono)
imagen que se debe utilizar en lugar de la imagen casilla de
JCheckBox (Icon,
verificacin por defecto de aspecto y tacto. Especificando el
boolean)
argumento booleano como trueinicializa la casilla de verificacin
JCheckBox (String,
que se seleccione. Si el argumento booleano est ausente o false,
Icon)
a continuacin, la casilla de verificacin est inicialmente sin
JCheckBox (String,
seleccionar.
Icon, boolean)
JCheckBox ()
JCheckBoxMenuItem
(Accin)
JCheckBoxMenuItem
(String) Crear una JCheckBoxMenuIteminstancia. Los argumentos se
JCheckBoxMenuItem interpretan de la misma manera que los argumentos de
(String, boolean) los JCheckBoxconstructores, excepto que cualquier icono
JCheckBoxMenuItem especificado se muestra en la adicin al icono normal de casilla de
(icono) verificacin.
JCheckBoxMenuItem
(String, Icon)
JCheckBoxMenuItem
(String, Icon, boolean)
JCheckBoxMenuItem
()
Constructores botn de opcin
Constructor Propsito
JRadioButton (Accin)
JRadioButton (String) Crear una JRadioButtoninstancia. El argumento de cadena
JRadioButton (String, especifica el texto, en su caso, de que el botn de radio debera
boolean) mostrar. Del mismo modo, el Iconargumento especifica la
JRadioButton (icono) imagen que se debe utilizar en lugar de la imagen del botn de
JRadioButton (Icon, radio por defecto de aspecto y tacto. Especificacin del
boolean) argumento booleano como trueinicializa el botn de seleccin
JRadioButton (String, para seleccionar, sujeto a la aprobacin
Icon) del ButtonGroupobjeto. Si el argumento booleano est ausente
JRadioButton (String, o false, a continuacin, el botn de opcin es inicialmente
Icon, boolean) seleccionada.
JRadioButton ()
JRadioButtonMenuItem
(Accin)
JRadioButtonMenuItem
Crear una JRadioButtonMenuIteminstancia. Los argumentos se
(String)
interpretan de la misma manera que los argumentos de
JRadioButtonMenuItem
los JRadioButtonconstructores, excepto que cualquier icono
(Icono)
especificado se muestra en la adicin al icono normal de botn
JRadioButtonMenuItem
de radio.
(String, Icono)
JRadioButtonMenuItem
()
Constructores botn de activacin
Constructor Propsito
JToggleButton
(Accin)
JToggleButton Crear un JToggleButtonejemplo, que es similar a una JButton, sino
(String) con dos estados. Normalmente, se utiliza
JToggleButton una JRadioButtono JCheckBoxen lugar de crear instancias
(String, boolean) directamente JToggleButton, pero JToggleButtonpuede ser til
JToggleButton cuando no se desea que el tpico botn de radio o comprobar el aspecto
(icono) caja. El argumento de cadena especifica el texto, en su caso, de que el
JToggleButton botn de activacin debe mostrar. Del mismo modo, el Iconargumento
(Icon, boolean) especifica la imagen que se debe utilizar. Especificando el argumento
JToggleButton booleano como trueinicializa el botn de activacin para ser
(String, Icon) seleccionados. Si el argumento booleano est ausente o false, a
JToggleButton continuacin, el botn de activacin est inicialmente seleccionada.
(String, Icon,
boolean)
JToggleButton ()
Comnmente botn usado Grupo de Constructores / Mtodos
Constructor o mtodo Propsito
ButtonGroup () Crear una ButtonGroupinstancia.
void add (AbstractButton)
void remove Aadir un botn para el grupo, o eliminar un botn del grupo.
(AbstractButton)
pblica ButtonGroup Obtener el ButtonGroup, en su caso, que controla un
getGroup () botn. Por ejemplo:
ButtonGroup group =
(en DefaultButtonModel ((DefaultButtonModel)button.getModel()).getGroup()
) ;
Borra el estado de los botones que aparecen en el
pblica ButtonGroup
ButtonGroup. Ninguno de los botones de la ButtonGroup se
clearSelection ()
seleccionan.

Ejemplos que usan varios tipos de botones

Los siguientes ejemplos usan botones. Vase tambin Ejemplos que usan la herramienta Bares , que
enumera los programas que aaden JButtonobjetos a JToolBars.

Ejemplo donde Descrito notas


Utiliza mnemotcnicos y los iconos. Especifica
ButtonDemo
Cmo utilizar la
la posicin de texto del botn, en relacin con el
API Botn Comn
icono del botn. Utiliza comandos de accin.
El uso de HTML en
ButtonHtmlDemo
Una versin de ButtonDemo que utiliza el
componentes de
formato HTML en sus botones.
Swing
ListDialog
Cmo utilizar las Implementa un dilogo con dos botones, uno de
funciones JButton los cuales es el botn predeterminado.
Ha "Mostrar que" botones cuyo comportamiento
est ligado al estado de los botones de
DialogDemo
Cmo crear
radio. Utiliza considerable, sin embargo, las
Dilogos
clases internas annimas para poner en prctica
los oyentes de accin.
ProgressBarDemo
Cmo monitorear el Implementa escucha la accin de un botn con
progreso una clase interna llamada.
Cmo utilizar los Utiliza los botones de la caja de verificacin para
CheckBoxDemo cuadros de determinar cul de las 16 imgenes que debe
marcacin mostrar.
ActionDemo
Cmo utilizar Utiliza los elementos del men de verificacin
acciones casilla para establecer el estado del programa.
RadioButtonDemo Cmo utilizar Utiliza los botones de radio para determinar cul
botones de opcin de cinco imgenes que debe mostrar.
Contiene varios juegos de botones de radio, que
DialogDemo
Cmo crear
utiliza para determinar cul de dilogo para que
Dilogos
aparezca.
MenuDemo
Cmo utilizar los Contiene elementos de men botn de radio y
mens elementos de men cheque caja.
ColorChooserDemo2
Cmo utilizar el Los lpices de colores en CrayonPanelse
color Selectores implementan como botones de conmutacin.
Cmo utilizar
ScrollDemo desplazamiento El cm botn es un botn de activacin.
Panes

Se puede obtener ms informacin sobre componentes de botn JavaFX de los siguientes documentos:

Uso de los controles de interfaz de usuario JavaFX: Botn


Uso de los controles de interfaz de usuario JavaFX: Radio Button
JavaFX utilizando la interfaz de usuario Controles: botn basculante
Uso de los controles de interfaz de usuario JavaFX: Casilla

Das könnte Ihnen auch gefallen