tema03
Differences
This shows you the differences between two versions of the page.
| Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
| tema03 [2026/11/12 13:59] – [Java Swing: imágenes en etiquetas y botones] mansky | tema03 [2026/11/12 14:01] (current) – [1. Preparar las imágenes] mansky | ||
|---|---|---|---|
| Line 165: | Line 165: | ||
| </ | </ | ||
| - | |||
| - | ===== 1. 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.** | ||
| - | |||
| - | ===== 2. 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. | ||
| - | |||
| - | ===== 3. 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. | ||
| - | |||
| - | ===== 4. 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: | ||
| - | |||
| - | ===== 5. 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**. | ||
| - | |||
| - | ===== 6. 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. | ||
| - | |||
| - | Es una simulación didáctica: no procesa pagos ni guarda pedidos. | ||
| - | |||
| - | ===== 7. 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); | ||
| - | } | ||
| - | }); | ||
| - | } | ||
| - | } | ||
| - | </ | ||
| - | |||
| - | ===== 8. Qué debemos entender ===== | ||
| - | |||
| - | * **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. | ||
tema03.1794491990.txt.gz · Last modified: by mansky
