首先我们看看源代码如下:
1 package cn.itcast_06; 2 3 import java.awt.Button; 4 import java.awt.Color; 5 import java.awt.FlowLayout; 6 import java.awt.Frame; 7 import java.awt.event.MouseAdapter; 8 import java.awt.event.MouseEvent; 9 import java.awt.event.WindowAdapter; 10 import java.awt.event.WindowEvent; 11 12 public class FrameDemo { 13 public static void main(String[] args) { 14 // 创建窗体对象 15 final Frame f = new Frame("更改背景色"); 16 // 设置窗体属性和布局 17 f.setBounds(400, 200, 400, 300); 18 f.setLayout(new FlowLayout()); 19 20 // 创建四个按钮 21 Button redButton = new Button("红色"); 22 Button greenButton = new Button("绿色"); 23 Button buleButton = new Button("蓝色"); 24 25 // 添加按钮 26 f.add(redButton); 27 f.add(greenButton); 28 f.add(buleButton); 29 30 // 设置窗体关闭 31 f.addWindowListener(new WindowAdapter() { 32 @Override 33 public void windowClosing(WindowEvent e) { 34 System.exit(0); 35 } 36 }); 37 38 // 对按钮添加动作事件,点击按钮 39 // redButton.addActionListener(new ActionListener() { 40 // @Override 41 // public void actionPerformed(ActionEvent e) { 42 // f.setBackground(Color.RED); 43 // } 44 // }); 45 46 // 对按钮添加鼠标点击事件,鼠标点击按钮,这与上面效果一样 47 // redButton.addMouseListener(new MouseAdapter() { 48 // @Override 49 // public void mouseClicked(MouseEvent e) { 50 // f.setBackground(Color.RED); 51 // } 52 // }); 53 54 // 对按钮添加鼠标的进入事件,鼠标箭头一旦进入按钮区域,就会触发事件 55 redButton.addMouseListener(new MouseAdapter() { 56 @Override 57 public void mouseEntered(MouseEvent e) { 58 f.setBackground(Color.RED); 59 } 60 }); 61 62 redButton.addMouseListener(new MouseAdapter() { 63 @Override 64 public void mouseExited(MouseEvent e) { 65 f.setBackground(Color.WHITE); 66 } 67 }); 68 69 greenButton.addMouseListener(new MouseAdapter() { 70 @Override 71 public void mouseEntered(MouseEvent e) { 72 f.setBackground(Color.GREEN); 73 } 74 }); 75 76 greenButton.addMouseListener(new MouseAdapter() { 77 @Override 78 public void mouseExited(MouseEvent e) { 79 f.setBackground(Color.WHITE); 80 } 81 }); 82 83 buleButton.addMouseListener(new MouseAdapter() { 84 @Override 85 public void mouseEntered(MouseEvent e) { 86 f.setBackground(Color.BLUE); 87 } 88 }); 89 90 buleButton.addMouseListener(new MouseAdapter() { 91 @Override 92 public void mouseExited(MouseEvent e) { 93 f.setBackground(Color.WHITE); 94 } 95 }); 96 97 // 设置窗体显示 98 f.setVisible(true); 99 } 100 }
运行结果如下:
当我们分别把鼠标放到红色、绿色、蓝色位置上的时候,颜色分别发生如下变化: