Led Switcher

 

 

Ho chiesto a ChatGpt:

 

crea un programma java che apre una finestra di 200 pixel x 200 pixel che ha un bottone in basso, al centro ci sarà una immagine che rappresenta un led rosso. Se si preme il bottone l'immagine verrà sostituita con una che rappresenta un led giallo. Se si preme di nuovo il bottone ritorna il led rosso. Le due immagini si chiamano rispettivamente led-rosso.jpg e led-giallo.jpg. Te ne allego una per fartela vedere. Mi dovresti indicare dove nel progetto in Netbeans dovrò collocare le immagini.

 

 

Classe: LedSwitcher

 1 package ledswitcher;
 2 
 3 import javax.swing.*;
 4 import java.awt.*;
 5 
 6 public class LedSwitcher {
 7 
 8     public static void main(String[] args) {
 9         JFrame frame = new JFrame();
10         frame.setSize(400, 400); // Imposta la finestra a 200x200 pixel
11         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12         frame.setLocationRelativeTo(null);
13         // Imposta il colore di sfondo della finestra a bianco (RGB: 255, 255, 255)
14         Color customBackgroundColor = new Color(255, 255, 255);
15         frame.getContentPane().setBackground(customBackgroundColor);
16 
17         ImageIcon redLed = new ImageIcon("img/led-rosso.jpg");
18         ImageIcon yellowLed = new ImageIcon("img/led-giallo.jpg");
19 
20         JLabel label = new JLabel();
21         label.setIcon(redLed);
22 
23         JButton button = new JButton("Switch");
24 
25         button.addActionListener(e -> {
26             if (label.getIcon() == redLed) {
27                 label.setIcon(yellowLed);
28             } else {
29                 label.setIcon(redLed);
30             }
31         });
32 
33         // Crea un nuovo pannello per l'etichetta e centralo sia in larghezza che in altezza
34         JPanel labelPanel = new JPanel(new GridBagLayout());
35         labelPanel.setOpaque(false); // Imposta il pannello come trasparente
36         labelPanel.add(label);
37 
38         // Aggiungi il pannello dell'etichetta e il pulsante al pannello principale
39         frame.add(labelPanel, BorderLayout.CENTER);
40         frame.add(button, BorderLayout.SOUTH);
41 
42         frame.setVisible(true);
43     }
44 }