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);
11 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12 frame.setLocationRelativeTo(null);
13
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
34 JPanel labelPanel = new JPanel(new GridBagLayout());
35 labelPanel.setOpaque(false);
36 labelPanel.add(label);
37
38
39 frame.add(labelPanel, BorderLayout.CENTER);
40 frame.add(button, BorderLayout.SOUTH);
41
42 frame.setVisible(true);
43 }
44 } |