public class Demo extends JFrame { JLabel label;//定义变量,以便在自定义方法类中调用 public Demo() { setBounds(100, 100, 300, 300); setResizable(false); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); //面板,黑色背景,以适应两张图片的黑色背景 JPanel panel = new JPanel(); panel.setBackground(Color.BLACK); c.add(panel); //Label,用来展示图片 label = new JLabel(); panel.add(label); //调用自定义方法类 addWindowFocusListener(new MyWindowFocusListener()); setVisible(true); } class MyWindowFocusListener implements WindowFocusListener { public void windowGainedFocus(WindowEvent e) { label.setIcon(new ImageIcon(Demo.class.getResource("light.png"))); } public void windowLostFocus(WindowEvent e) { label.setIcon(new ImageIcon(Demo.class.getResource("dark.png"))); } } public static void main(String[] args) { new Demo(); } }