Cómo usar Action Events en Swing?
Action events occurren cuando un usuario completa una accíon usando alguno de los siguientes componentes: JTextField, JCheckBox, JComboBox, JRadioButton, JButton.
Una clase debe implementar la interface ActionListener para manejar los eventos. El método actionPerformed(ActionEvent) es el único método de la interface ActionListener
Veamos el siguiente ejemplo:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class AplicSwing implements ActionListener {
private static String lbl = «Número de clicks en el botón «;
private int numClicks = 0;
final JLabel jlabel = new JLabel(lbl + «0 «);
public Component createComponents() {
JButton boton = new JButton(«Botón swing»);
boton.setMnemonic(KeyEvent.VK_I);
boton.addActionListener(this);
jlabel.setLabelFor(boton);
JPanel pane = new JPanel(new GridLayout(0, 1));
pane.add(boton);
pane.add(jlabel);
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);
return pane;
}
public void actionPerformed(ActionEvent e) {
numClicks++;
jlabel.setText(lbl + numClicks);
}
/*Creamos el GUI para mostrar el botón
*/
private static void gui() {
//Decoramos el frame
JFrame.setDefaultLookAndFeelDecorated(true);
//Creamos la ventana
JFrame frame = new JFrame(«Aplicación swing»);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
AplicSwing app = new AplicSwing();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
//Mostramos ventana
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
gui();
}
});
}
}
Deja un comentario
Lo siento, debes estar conectado para publicar un comentario.