tema02
Differences
This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| tema02 [2026/11/12 13:54] – created mansky | tema02 [2026/11/12 21:14] (current) – [8. Qué debemos entender] mansky | ||
|---|---|---|---|
| Line 253: | Line 253: | ||
| Lo mismo sucede con fill, weightx y las demás propiedades. Modificar c para el siguiente componente **no modifica los componentes que ya se han añadido**. | Lo mismo sucede con fill, weightx y las demás propiedades. Modificar c para el siguiente componente **no modifica los componentes que ya se han añadido**. | ||
| - | ===== 11. Actividades | + | ===== EJEMPLO ===== |
| + | |||
| + | Vamos a crear una tienda de informática con **GridBagLayout**. Mostrará la imagen de un ratón en un **JLabel** y un icono de carrito en un **JButton**. | ||
| + | |||
| + | ===== Preparar las imágenes ===== | ||
| + | |||
| + | En Eclipse, crear un paquete llamado **imagenes** dentro de **src** y copiar en él los siguientes archivos: | ||
| + | |||
| + | ^ Archivo ^ Uso ^ Tamaño orientativo ^ | ||
| + | | raton.png | Fotografía del producto | 160 × 120 píxeles | | ||
| + | | carrito.png | Icono del botón Comprar | 24 × 24 píxeles | | ||
| + | |||
| + | Respetar los nombres y las mayúsculas. En este ejemplo se muestran las imágenes con su tamaño original. **Estas imágenes debe aportarlas el alumnado; no están incluidas en esta página.** | ||
| + | |||
| + | ===== Cargar una imagen con ImageIcon ===== | ||
| + | |||
| + | <code java> | ||
| + | ImageIcon imagen = new ImageIcon( | ||
| + | getClass().getResource("/ | ||
| + | </ | ||
| + | |||
| + | La ruta comienza por / porque se busca desde la raíz de los recursos del classpath. No es una ruta absoluta del disco. | ||
| + | |||
| + | En un proyecto Java habitual de Eclipse, los recursos situados en src se copian a la carpeta de salida al compilar. | ||
| + | |||
| + | ===== Imagen en un JLabel ===== | ||
| + | |||
| + | <code java> | ||
| + | JLabel lblImagen = new JLabel(imagen); | ||
| + | lblImagen.setToolTipText(" | ||
| + | </ | ||
| + | |||
| + | La etiqueta muestra la imagen. El texto de ayuda aparece al mantener el puntero sobre ella. | ||
| + | |||
| + | ===== Imagen y texto en un JButton ===== | ||
| + | |||
| + | <code java> | ||
| + | ImageIcon iconoCarrito = new ImageIcon( | ||
| + | getClass().getResource("/ | ||
| + | |||
| + | JButton btnComprar = new JButton(" | ||
| + | btnComprar.setHorizontalTextPosition(SwingConstants.RIGHT); | ||
| + | btnComprar.setVerticalTextPosition(SwingConstants.CENTER); | ||
| + | btnComprar.setIconTextGap(8); | ||
| + | </ | ||
| + | |||
| + | * **setHorizontalTextPosition: | ||
| + | * **setVerticalTextPosition: | ||
| + | * **setIconTextGap: | ||
| + | |||
| + | ===== Distribución de la tienda ===== | ||
| + | |||
| + | ^ Fila ^ Columna 0 ^ Columna 1 ^ | ||
| + | | 0 | Imagen del ratón (abarca filas 0–2) | Nombre del producto | | ||
| + | | 1 | Continuación de la imagen | Precio | | ||
| + | | 2 | Continuación de la imagen | Casilla de envoltorio | | ||
| + | | 3 | Total: | Importe | | ||
| + | | 4 | Botón Comprar con icono (abarca dos columnas) || | ||
| + | |||
| + | La imagen usa **gridheight = 3** y el botón usa **gridwidth = 2**. | ||
| + | |||
| + | ===== Funcionamiento ===== | ||
| + | |||
| + | - El ratón cuesta **19,90 €**. | ||
| + | - El envoltorio añade **2,00 €**. | ||
| + | - Al marcar o desmarcar la casilla, el total se actualiza. | ||
| + | - Al pulsar Comprar, aparece el resumen del pedido. | ||
| + | |||
| + | ===== Código completo ===== | ||
| + | |||
| + | Crear una clase llamada **TiendaImagenes**: | ||
| + | |||
| + | <code java> | ||
| + | import java.awt.GridBagConstraints; | ||
| + | import java.awt.GridBagLayout; | ||
| + | import java.awt.Insets; | ||
| + | import java.awt.event.ActionEvent; | ||
| + | import java.awt.event.ActionListener; | ||
| + | import java.awt.event.ItemEvent; | ||
| + | import java.awt.event.ItemListener; | ||
| + | import java.util.Locale; | ||
| + | import javax.swing.ImageIcon; | ||
| + | import javax.swing.JButton; | ||
| + | import javax.swing.JCheckBox; | ||
| + | import javax.swing.JFrame; | ||
| + | import javax.swing.JLabel; | ||
| + | import javax.swing.JOptionPane; | ||
| + | import javax.swing.JPanel; | ||
| + | import javax.swing.SwingConstants; | ||
| + | import javax.swing.SwingUtilities; | ||
| + | |||
| + | public class TiendaImagenes extends JFrame { | ||
| + | private JCheckBox chkEnvoltorio; | ||
| + | private JLabel lblTotal; | ||
| + | |||
| + | // Importes en céntimos para calcular con enteros. | ||
| + | private static final int PRECIO_RATON = 1990; | ||
| + | private static final int PRECIO_ENVOLTORIO = 200; | ||
| + | |||
| + | public TiendaImagenes() { | ||
| + | setTitle(" | ||
| + | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | ||
| + | |||
| + | JPanel panel = new JPanel(new GridBagLayout()); | ||
| + | setContentPane(panel); | ||
| + | GridBagConstraints c = new GridBagConstraints(); | ||
| + | c.insets = new Insets(10, 10, 10, 10); | ||
| + | |||
| + | // Cargar los recursos del proyecto. | ||
| + | ImageIcon imagenRaton = new ImageIcon( | ||
| + | getClass().getResource("/ | ||
| + | ImageIcon iconoCarrito = new ImageIcon( | ||
| + | getClass().getResource("/ | ||
| + | |||
| + | // Imagen: una columna y tres filas. | ||
| + | JLabel lblImagen = new JLabel(imagenRaton); | ||
| + | lblImagen.setToolTipText(" | ||
| + | c.gridx = 0; | ||
| + | c.gridy = 0; | ||
| + | c.gridheight = 3; | ||
| + | c.anchor = GridBagConstraints.CENTER; | ||
| + | panel.add(lblImagen, | ||
| + | |||
| + | // Nombre. | ||
| + | JLabel lblNombre = new JLabel(" | ||
| + | c.gridx = 1; | ||
| + | c.gridy = 0; | ||
| + | c.gridheight = 1; // Restablecer después de la imagen. | ||
| + | c.weightx = 1.0; | ||
| + | c.fill = GridBagConstraints.HORIZONTAL; | ||
| + | c.anchor = GridBagConstraints.WEST; | ||
| + | panel.add(lblNombre, | ||
| + | |||
| + | // Precio. | ||
| + | JLabel lblPrecio = new JLabel(" | ||
| + | c.gridy = 1; | ||
| + | panel.add(lblPrecio, | ||
| + | |||
| + | // Opción adicional. | ||
| + | chkEnvoltorio = new JCheckBox( | ||
| + | " | ||
| + | c.gridy = 2; | ||
| + | panel.add(chkEnvoltorio, | ||
| + | |||
| + | // Etiqueta Total. | ||
| + | c.gridx = 0; | ||
| + | c.gridy = 3; | ||
| + | c.weightx = 0.0; | ||
| + | c.fill = GridBagConstraints.NONE; | ||
| + | panel.add(new JLabel(" | ||
| + | |||
| + | // Importe. | ||
| + | lblTotal = new JLabel(formatearPrecio(PRECIO_RATON)); | ||
| + | c.gridx = 1; | ||
| + | c.weightx = 1.0; | ||
| + | c.fill = GridBagConstraints.HORIZONTAL; | ||
| + | panel.add(lblTotal, | ||
| + | |||
| + | // Botón con icono y texto. | ||
| + | JButton btnComprar = new JButton(" | ||
| + | btnComprar.setHorizontalTextPosition(SwingConstants.RIGHT); | ||
| + | btnComprar.setVerticalTextPosition(SwingConstants.CENTER); | ||
| + | btnComprar.setIconTextGap(8); | ||
| + | c.gridx = 0; | ||
| + | c.gridy = 4; | ||
| + | c.gridwidth = 2; | ||
| + | c.fill = GridBagConstraints.HORIZONTAL; | ||
| + | panel.add(btnComprar, | ||
| + | |||
| + | // Actualizar al marcar o desmarcar la casilla. | ||
| + | chkEnvoltorio.addItemListener(new ItemListener() { | ||
| + | @Override | ||
| + | public void itemStateChanged(ItemEvent e) { | ||
| + | lblTotal.setText(formatearPrecio(calcularTotal())); | ||
| + | } | ||
| + | }); | ||
| + | |||
| + | btnComprar.addActionListener(new ActionListener() { | ||
| + | @Override | ||
| + | public void actionPerformed(ActionEvent e) { | ||
| + | String envoltorio = " | ||
| + | if (chkEnvoltorio.isSelected()) { | ||
| + | envoltorio = " | ||
| + | } | ||
| + | JOptionPane.showMessageDialog( | ||
| + | TiendaImagenes.this, | ||
| + | " | ||
| + | + " | ||
| + | + " | ||
| + | " | ||
| + | JOptionPane.INFORMATION_MESSAGE); | ||
| + | } | ||
| + | }); | ||
| + | |||
| + | pack(); | ||
| + | setLocationRelativeTo(null); | ||
| + | } | ||
| + | |||
| + | private int calcularTotal() { | ||
| + | int total = PRECIO_RATON; | ||
| + | if (chkEnvoltorio.isSelected()) { | ||
| + | total += PRECIO_ENVOLTORIO; | ||
| + | } | ||
| + | return total; | ||
| + | } | ||
| + | |||
| + | private String formatearPrecio(int centimos) { | ||
| + | return String.format( | ||
| + | new Locale(" | ||
| + | } | ||
| + | |||
| + | public static void main(String[] args) { | ||
| + | SwingUtilities.invokeLater(new Runnable() { | ||
| + | @Override | ||
| + | public void run() { | ||
| + | new TiendaImagenes().setVisible(true); | ||
| + | } | ||
| + | }); | ||
| + | } | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | ===== Puntos Importantes ===== | ||
| + | |||
| + | * **JLabel(imagenRaton)** muestra la fotografía. | ||
| + | * **JButton(" | ||
| + | * **gridheight = 3** hace que la imagen abarque tres filas. | ||
| + | * **gridwidth = 2** hace que el botón abarque dos columnas. | ||
| + | * **fill estira el componente, pero no redimensiona la imagen.** | ||
| + | * **ItemListener** detecta los cambios de selección de la casilla. | ||
| + | * **ActionListener** responde a la pulsación del botón. | ||
| + | * Los cálculos se realizan en céntimos; la conversión a euros se hace al presentar el resultado. | ||
| + | * **SwingUtilities.invokeLater** crea la interfaz en el hilo de eventos de Swing. | ||
| - | - Ampliar horizontalmente la ventana y comprobar que crecen los campos y el botón. | ||
| - | - Cambiar el fill del botón a NONE: seguirá abarcando dos columnas, pero conservará su ancho preferido si hay espacio suficiente. | ||
| - | - Con fill = NONE, cambiar su anchor a EAST y observar la alineación. | ||
| - | - Añadir una fila Teléfono con su campo de texto. | ||
| - | - Añadir dos botones en la última fila: Guardar y Limpiar, uno por columna. Restablecer gridwidth = 1. | ||
| - | - Programar Limpiar para vaciar los campos y desmarcar la casilla. | ||
tema02.1794491647.txt.gz · Last modified: by mansky
