GUI_通過滑鼠移動到按鈕上更改背景色案例
阿新 • • 發佈:2019-01-29
package cn.itcast_06; import java.awt.Button; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class FrameDemo { public static void main(String[] args) { // 建立窗體物件 final Frame f = new Frame("更改背景顏色"); // 設定屬性及佈局 f.setBounds(400, 200, 400, 300); f.setLayout(new FlowLayout()); // 建立按鈕物件 Button redButton = new Button("紅色"); Button greenButton = new Button("綠色"); Button blueButton = new Button("藍色"); Button whiteButton = new Button("復原"); // 新增按鈕 f.add(redButton); f.add(greenButton); f.add(blueButton); f.add(whiteButton); // 對按鈕新增動作事件 // redButton.addActionListener(new ActionListener() { // // @Override // public void actionPerformed(ActionEvent e) { // f.setBackground(Color.RED); // } // }); // 對按鈕新增滑鼠點選事件 // redButton.addMouseListener(new MouseAdapter() { // @Override // public void mouseClicked(MouseEvent e) { // f.setBackground(Color.RED); // } // }); // 對按鈕新增滑鼠的進入事件 redButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { f.setBackground(Color.RED); } // @Override // public void mouseExited(MouseEvent e) { // f.setBackground(Color.WHITE); // } }); greenButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { f.setBackground(Color.GREEN); } // @Override // public void mouseExited(MouseEvent e) { // f.setBackground(Color.WHITE); // } }); blueButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { f.setBackground(Color.BLUE); } // @Override // public void mouseExited(MouseEvent e) { // f.setBackground(Color.WHITE); // } }); whiteButton.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { f.setBackground(Color.WHITE); } // @Override // public void mouseExited(MouseEvent e) { // f.setBackground(Color.WHITE); // } }); // 設定關閉窗體 f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); // 設定窗體可見 f.setVisible(true); } }