JAVA SWING
Sistemas de Informacion
JavaSwing
Java Swing es el toolkit de widgets de las Java Foundation Classes (JFC) para crear interfaces
gráficas de usuario (GUI) en aplicaciones de escritorio Java. Incluye componentes como ventanas,
botones, etiquetas y campos de texto, con comportamiento consistente entre plataformas.[1][2][3]
Qué es Swing
Swing forma parte de JFC y se apoya en la infraestructura de AWT, heredando su modelo de
eventos para manejar teclado, ratón y otras interacciones. Proporciona un conjunto amplio de
componentes “ligeros” con apariencia y comportamiento personalizables mediante gestores de
“Look & Feel”. Su paquete principal es javax.swing y nombra las clases con prefijo J, como
JFrame y JButton.[3][1]
Componentes y contenedores
• JFrame: ventana de nivel superior para alojar la interfaz principal.[3]
• JPanel: contenedor ligero para organizar otros componentes.[3]
• JButton: botón interactivo que dispara acciones.[2]
• JLabel: muestra texto o iconos no editables.[2]
• JTextField y JPasswordField: entradas de texto de una línea.[2]
• JTextArea: área de texto multilínea.[2]
• JRadioButton y JCheckBox: opciones seleccionables.[2]
• JOptionPane: cuadros de diálogo estándar para mensajes e inputs.[2]
Layouts y eventos
La disposición visual se gestiona con “layout managers” como BorderLayout, FlowLayout y
GridBagLayout para controlar posiciones y redimensiones de componentes. Los eventos se
manejan con “listeners” como ActionListener, MouseListener, WindowListener y otros,
ROCKS 1
JAVA SWING
conectando interacciones del usuario con lógica de la aplicación. Un botón, por ejemplo, puede
registrar un ActionListener para ejecutar código al hacer clic.[3]
Hilo de eventos (EDT)
Swing sigue la “regla de un solo hilo”: la mayoría de los métodos no son thread-safe y deben
invocarse únicamente desde el hilo de despacho de eventos (EDT) a través de manejadores de
eventos. Algunos métodos están marcados como “thread-safe”, pero son la excepción; manipular
la UI desde otros hilos puede causar comportamientos indefinidos. El patrón recomendado es crear
y actualizar la GUI en el EDT y responder a eventos dentro de sus listeners.[3]
Ejemplo mínimo
El siguiente ejemplo crea un JFrame con un JButton que muestra un JOptionPane al pulsarlo,
utilizando un layout estándar y un ActionListener como en la documentación referida.[3][2]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HolaSwing {
public static void main(String[] args) {
JFrame frame = new JFrame("Hola Swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new BorderLayout());
JLabel etiqueta = new JLabel("Hola Mundo", SwingConstants.CENTER);
JButton boton = new JButton("Saludar");
boton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "¡Hola desde Swing!");
}
});
ROCKS 2
JAVA SWING
panel.add(etiqueta, BorderLayout.CENTER);
panel.add(boton, BorderLayout.SOUTH);
frame.setContentPane(panel);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Este patrón usa contenedores, un BorderLayout, y un ActionListener para conectar la interacción
del botón con un cuadro de diálogo estándar.[2][3]
Look and Feel
Swing permite cambiar dinámicamente el “Look & Feel”, por ejemplo con
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()) para un
estilo consistente entre plataformas o el nativo del sistema.[3]
Aprende más
• Oracle: “Creating a GUI with Swing” (tutorial oficial paso a paso).[4]
• Wikipedia: “Swing (Java)” para contexto y alcance dentro de JFC.[1]
• Universidad de Chile: guía en español con eventos, layouts y regla de un hilo.[3]
• Introducción y componentes comunes explicados en español (Alura).[2]
• Tutorial en español con ejemplos prácticos (Oregoom).[5]
Cómo crear una ventana básica con JFrame en Java Swing
La forma más simple es crear un JFrame, configurar la operación de cierre, añadir al menos un
componente, ajustar el tamaño con pack, centrarlo con setLocationRelativeTo(null) y mostrarlo,
todo ello inicializado en el hilo de despacho de eventos con SwingUtilities.invokeLater. Esto
ROCKS 3
JAVA SWING
asegura un comportamiento correcto de la GUI y sigue las recomendaciones oficiales de los
tutoriales de Swing de Oracle.[11][12]
Pasos rápidos
• Define un método que construya el JFrame, configure
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE), añada algún componente al content
pane y llame a pack y setVisible(true).[11]
• En el método main, programa la creación de la GUI con SwingUtilities.invokeLater(() ->
createAndShowGUI()) para ejecutarla en el Event Dispatch Thread (EDT).[12]
• Usa frame.pack() para dimensionar según los tamaños preferidos de los componentes;
después centra con frame.setLocationRelativeTo(null) y por último llama a
setVisible(true).[11]
Ejemplo mínimo
import javax.swing.*;
import java.awt.*;
public class VentanaBasica {
private static void createAndShowGUI() {
JFrame frame = new JFrame("Ventana básica");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Hola Swing", SwingConstants.CENTER), BorderLayout.CENTER);
frame.pack(); // ajusta al tamaño preferido de los componentes
frame.setLocationRelativeTo(null); // centra en la pantalla
frame.setVisible(true); // muestra la ventana
}
public static void main(String[] args) {
SwingUtilities.invokeLater(VentanaBasica::createAndShowGUI);
ROCKS 4
JAVA SWING
}
}
Este ejemplo crea y muestra el frame en el EDT, utiliza pack para un tamaño correcto, centra la
ventana y define la operación de cierre con EXIT_ON_CLOSE según las guías de Oracle.[12][11]
Opciones útiles
• En lugar de pack, puedes fijar un tamaño concreto con setSize(ancho, alto) cuando necesites
dimensiones específicas.[11]
• Puedes ajustar el título y aspectos de la ventana con setTitle, setIconImage y (de forma
global) setDefaultLookAndFeelDecorated antes de crear frames.[11]
• Si tu aplicación abre varias ventanas, considera DISPOSE_ON_CLOSE para cerrar solo esa
ventana y no terminar todo el proceso, reservando EXIT_ON_CLOSE para aplicaciones con
una única ventana principal.[13][14]
Errores comunes
• Crear y actualizar componentes de Swing fuera del EDT puede provocar comportamientos
indefinidos; programa la creación de la GUI con SwingUtilities.invokeLater o
invokeAndWait según corresponda.[12]
• Llamar setVisible(true) antes de pack o de establecer la posición puede resultar en tamaños o
ubicaciones inesperadas; realiza pack, luego setLocationRelativeTo(null) y finalmente
setVisible(true).[11]
• Olvidar setDefaultCloseOperation hace que el cierre con el botón X no termine la aplicación
(por defecto se comporta como HIDE_ON_CLOSE), de modo que suele ser necesario
establecer EXIT_ON_CLOSE o DISPOSE_ON_CLOSE explícitamente.[15]
Referencias rápidas (Oracle)
• How to Make Frames: pasos y métodos clave como pack, setDefaultCloseOperation y
setLocationRelativeTo.[11]
ROCKS 5
JAVA SWING
• Initial Threads (Swing): por qué usar SwingUtilities.invokeLater/invokeAndWait para crear
la GUI en el EDT.[12]
Eventos más comunes Dentro del De JavaSwing
Los eventos más comunes en Java Swing son ActionEvent, MouseEvent, KeyEvent, FocusEvent,
ChangeEvent, DocumentEvent y WindowEvent, y se manejan con sus oyentes correspondientes
como ActionListener, MouseListener, KeyListener, FocusListener, ChangeListener,
DocumentListener y WindowListener. Estos eventos representan interacciones del usuario o
cambios de estado y pueden dispararse desde el componente o desde su modelo de datos asociado
según el caso.[31][32]
Modelo de eventos
El modelo de delegación de eventos se compone de fuente (componente), objeto evento y oyente
registrado que reacciona al producirse el evento. La fuente genera el evento y lo notifica al
Listener correspondiente, que implementa la interfaz adecuada para ejecutar la acción
deseada.[33][31]
Eventos y listeners
• ActionEvent → ActionListener: Acciones como clic en JButton, seleccionar JMenuItem o
pulsar Enter en JTextField, atendidas en actionPerformed.[31][33]
• MouseEvent → MouseListener/MouseMotionListener: Clics, pressed/released, enter/exit, y
movimiento/arrastre del ratón sobre componentes.[31]
• KeyEvent → KeyListener: Detección de teclas con keyPressed, keyReleased y keyTyped.[31]
• FocusEvent → FocusListener: Cambios de foco con focusGained y focusLost.[31]
• ChangeEvent → ChangeListener: Cambios en componentes como JSlider, JTabbedPane o
JSpinner.[31]
• DocumentEvent → DocumentListener: Cambios en el contenido de JTextField/JTextArea y
otros JTextComponent.[31]
ROCKS 6
JAVA SWING
• WindowEvent → WindowListener: Apertura, cierre, iconificación y otras transiciones de
ventana.[31]
• WindowStateEvent → WindowStateListener: Cambios de estado de la ventana como
minimizar o maximizar.[31]
Registro de listeners
El patrón general es registrar el oyente en la fuente con métodos como addActionListener,
addMouseListener, addKeyListener, addFocusListener, addChangeListener,
getDocument().addDocumentListener o addWindowListener según el tipo de evento. Un mismo
componente puede tener varios oyentes y un oyente puede estar registrado en múltiples fuentes, lo
que facilita separar responsabilidades de manejo de eventos. Muchos componentes disparan
eventos desde su modelo (por ejemplo, documentos de texto), por lo que conviene revisar qué
listeners soporta cada componente concreto.[32][33]
Ejemplos breves
// ActionEvent en un JButton
JButton boton = new JButton("Guardar");
boton.addActionListener(e -> System.out.println("Guardado"));
// DocumentEvent en un JTextField
JTextField campo = new JTextField(20);
campo.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) { validar(); }
public void removeUpdate(DocumentEvent e) { validar(); }
public void changedUpdate(DocumentEvent e) { validar(); }
private void validar() { /* lógica de validación */ }
});
Estos ejemplos muestran el registro típico con addActionListener para acciones y
DocumentListener para cambios en texto, que son dos de los casos más usados en
formularios.[33][31]
ROCKS 7
JAVA SWING
Buenas prácticas
• Manipula la UI en el Event Dispatch Thread (EDT) porque Swing no es thread-safe y los
listeners se ejecutan en ese hilo de eventos.[34]
• Para interceptar el cierre de ventanas, usa un WindowListener y configura la operación de
cierre apropiada como DISPOSE_ON_CLOSE para liberar recursos sin terminar el proceso
completo.[35][31]
Referencias
1. https://translate.google.com/translate?u=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FS
wing_(Java)&hl=es&sl=en&tl=es&client=srp
2. https://www.aluracursos.com/blog/biblioteca-swing
3. https://users.dcc.uchile.cl/~lmateu/CC60H/Trabajos/edavis/swing.html
4. https://translate.google.com/translate?u=https%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ft
utorial%2Fuiswing%2Findex.html&hl=es&sl=en&tl=es&client=srp
5. https://oregoom.com/java/swing/
6. https://translate.google.com/translate?u=https%3A%2F%2Fhappycoding.io%2Ftutorials%2F
java%2Fswing&hl=es&sl=en&tl=es&client=srp
7. https://translate.google.com/translate?u=https%3A%2F%2Fwww.geeksforgeeks.org%2Fjava
%2Fintroduction-to-java-swing%2F&hl=es&sl=en&tl=es&client=srp
8. https://www.youtube.com/watch?v=6YYmZ8cQc7o
9. https://www.youtube.com/watch?v=HrEiL-2cokw
10. https://www.youtube.com/watch?v=IUHd-UOxT0s
11. https://docs.oracle.com/javase/tutorial/uiswing/components/frame.html
12. https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
ROCKS 8
JAVA SWING
13. https://javaprogramming.language-tutorial.com/2012/09/jframe-exitonclose-vs-
disposeonclose.html
14. https://www.clear.rice.edu/comp310/JavaResources/frame_close.html
15. https://stackoverflow.com/questions/7799940/jframe-exit-on-close-java
16. https://stackoverflow.com/questions/22313120/swingutilities-invokelater-takes-a-runnable-
and-runs-it-on-the-edt
17. https://forums.oracle.com/ords/apexds/post/move-objects-into-a-frame-1226
18. https://javarevisited.blogspot.com/2011/09/invokeandwait-invokelater-swing-example.html
19. https://www.youtube.com/watch?v=Xb-Znv3tEgw
20. https://www.reddit.com/r/learnprogramming/comments/1jnsvc/what_does_swingutilitiesinvo
kelater_do_java/
21. https://www.tek-tips.com/threads/repeating-frame.818099/
22. https://www.reddit.com/r/learnprogramming/comments/29ik8n/java_can_someone_explain/
23. https://coderanch.com/t/653871/java/GUI-close-press-setDefaultCloseOperation-JFrame
24. https://docs.oracle.com/cd/F26413_61/books/ConfigApps/c-Guidelines-for-Creating-HTML-
Frames-in-a-Container-Page-ai1073012.html
25. https://es.stackoverflow.com/questions/159433/invokelater-runnable-obj-duda
26. https://www.tutorialesprogramacionya.com/javaya/detalleconcepto.php?codigo=104&punto
=&inicio=20
27. https://docs.oracle.com/cd/E92519_02/pt856pbr3/eng/pt/tapd/task_UsingFrames-
0775af.html?pli=ul_d24e164_tapd
28. https://docs.oracle.com/javase/8/docs/api/java/awt/Frame.html
ROCKS 9
JAVA SWING
29. https://stackoverflow.com/questions/7719395/how-to-create-block-frames-in-oracle-forms-
10g
30. https://docs.oracle.com/javase/tutorial/uiswing/components/internalframe.html
31. https://www.universojava.com/2022/11/eventos-de-java-swing.html
32. https://translate.google.com/translate?u=https%3A%2F%2Fdocs.oracle.com%2Fjavase%2Ft
utorial%2Fuiswing%2Fevents%2Feventsandcomponents.html&hl=es&sl=en&tl=es&client=
srp
33. https://www.buscaminegocio.com/cursos-de-java/manejo-de-eventos-swing.html
34. https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
35. https://www.clear.rice.edu/comp310/JavaResources/frame_close.html
36. https://www.jairogarciarincon.com/clase/interfaces-de-usuario-con-java-swing/eventos-y-
componente-jbutton
37. https://translate.google.com/translate?u=https%3A%2F%2Fblog.jyotiprakash.org%2Fintrod
uction-to-swing&hl=es&sl=en&tl=es&client=srp
38. https://translate.google.com/translate?u=https%3A%2F%2Fvictomanolo.wordpress.com%2F
eventos-en-java%2F&hl=es&sl=en&tl=es&client=srp
39. https://javajhon.blogspot.com/2020/10/swing-b.html
40. https://translate.google.com/translate?u=https%3A%2F%2Fwww.tutorialspoint.com%2Fswi
ng%2Fswing_event_handling.htm&hl=es&sl=en&tl=es&client=srp
41. https://www.youtube.com/watch?v=uQWVgMeOeHw
42. http://codejavu.blogspot.com/2013/09/componentes-java-swing.html
ROCKS 10