
Ejemplo de Ventana Swing con Eventos
Java
Publicado el 3 de Septiembre del 2012 por Administrador (718 códigos)
11.202 visualizaciones desde el 3 de Septiembre del 2012
Ejemplo de cómo recoger eventos de componentes.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class VentanaPrueba extends JFrame implements ActionListener
{
private JButton btnAceptar;
private JButton btnCancelar;
JTextField txtNombre;
JTextField txtEdad;
public static void main(String[] args)
{
VentanaPrueba vp = new VentanaPrueba();
}
public VentanaPrueba()
{
JLabel lblNombre = new JLabel("Nombre: ");
txtNombre = new JTextField(10);
JLabel lblEdad = new JLabel("Edad: ");
txtEdad = new JTextField(2);
btnAceptar = new JButton ("Aceptar");
btnCancelar= new JButton ("Cancelar");
btnAceptar.addActionListener(this);
btnCancelar.addActionListener(this);
this.setLayout(new GridLayout(3, 2));
this.add(lblNombre);
this.add(txtNombre);
this.add(lblEdad);
this.add(txtEdad);
this.add(btnAceptar);
this.add(btnCancelar);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setSize(200, 200);
this.setTitle("ererererer");
this.setResizable(false);
//this.setSize(new Dimension(300,200));
this.pack();
this.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==btnAceptar)
{
// System.out.println(txtNombre.getText()); NUNCA se debe utilizar
StringBuilder sb = new StringBuilder("Nombre: ");
sb.append(txtNombre.getText());
sb.append("\nEdad: ");
sb.append(txtEdad.getText());
JOptionPane.showMessageDialog(this, sb.toString(), "Información de la Persona", JOptionPane.INFORMATION_MESSAGE);
}
else if(e.getSource()==btnCancelar)
{
txtNombre.setText("");
txtEdad.setText("");
}
}
}
Comentarios sobre la versión: Versión 1 (0)
No hay comentarios