Ejemplo Swing Java 1
package ejswing1;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/*
1 – Creamos 1 botón, con JButton
2 – Usamos setBounds
3 – lo metemos en el frame con .add
4 – añadimos «extends JFrame implements ActionListener» a la clase principal
5 – Usamos .addActionListener con el botón
6 – Autocompletar cuando proceda
*/
public class EjSwing1 extends JFrame implements ActionListener {
JFrame ventana = new JFrame();
JLabel label1 = new JLabel(«Etiqueta1»);
JLabel label2 = new JLabel(«Etiqueta2»);
JLabel label3 = new JLabel(«Etiqueta3»);
JButton botonsalir = new JButton(«Salir»);
JButton boton2 = new JButton(«Boton2»);
JButton boton3 = new JButton(«Boton3»);
JButton boton4 = new JButton();
public void graficos() {
ventana.setLayout(null);
ventana.setSize(600,600);
ventana.setVisible(true);
label1.setBounds(30, 0, 100, 50);
label2.setBounds(30, 50, 100, 50);
label3.setBounds(30, 100, 100, 50);
botonsalir.setBounds(130, 0, 100, 50);
boton2.setBounds(130, 50, 100, 50);
boton3.setBounds(130, 100, 100, 50);
boton4.setBounds(130, 150, 100, 50);
boton4.setText(«Cambiar»);
ventana.add(label1);
ventana.add(label2);
ventana.add(label3);
ventana.add(botonsalir);
ventana.add(boton2);
ventana.add(boton3);
ventana.add(boton4);
// al escribir «sleep» se me ha autocompletado la siguiente línea
// y también la parte del main «throws Interrumped…»
/*Thread.sleep(3000);
System.exit(0);*/
// después de «implements» y del action perfomed, debemos añadir esto
botonsalir.addActionListener(this);
boton4.addActionListener(this);
}
public static void main(String[] args) {
EjSwing1 nuevo = new EjSwing1();
nuevo.graficos();
}
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource()==botonsalir) {
System.exit(0);
}
if (ae.getSource()==boton4) {
label3.setText(«Nuevo texto»);
}
}
}