Beruflich Dokumente
Kultur Dokumente
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:
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.
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
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.
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.
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
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.
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();
}
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,
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.
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.
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:
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.
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
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.
// 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
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:
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.
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:
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);
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
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.
// 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);
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 .
Los siguientes ejemplos usan botones. Vase tambin Ejemplos que usan la herramienta Bares , que
enumera los programas que aaden JButtonobjetos a JToolBars.
Se puede obtener ms informacin sobre componentes de botn JavaFX de los siguientes documentos: