題目:
編寫一個程序,創建一個AWT面板,該面板包含三個不同顏色名稱的三個按鈕,單擊每個按鈕時應使窗口的背景顏色顯示為相應的顏色。程序運行的結果如下:
源程序如下:
import java.awt.*;
import java.awt.event.*;
import javax.swing.JButton;
class ChangeBgColor extends Frame implements ActionListener {
private static final long serialVersionUID = 1L; Panel p;
JButton btn1,btn2,btn3; ChangeBgColor() {
p = new Panel(); btn1 = new JButton("紅色");
btn1.setBackground(Color.red ); btn2 = new JButton("藍色");
btn2.setBackground(Color.blue);
btn3 = new JButton("黃色");
btn3.setBackground(Color.yellow); this.add(p); p.add(btn1); p.add(btn2); p.add(btn3);
btn1.addActionListener(this); btn2.addActionListener(this); btn3.addActionListener(this); }
public static void main(String args[]) {
ChangeBgColor mainFrame = new ChangeBgColor(); mainFrame.setTitle("基本GUI 編程"); mainFrame.setSize(400, 400);
mainFrame.setLocation(100, 100);
mainFrame.setBackground(Color.black); mainFrame.setVisible(true);
mainFrame.addWindowListener(new MyClosing()); }
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn1) {
p.setBackground(Color.red); }
else if(e.getSource() == btn2) {
p.setBackground(Color.blue); } else
p.setBackground(Color.yellow); } }
class MyClosing implements WindowListener {
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) {
System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowOpened(WindowEvent e) { } }
想要更多的企業求職加分項目案例,關注Java學習交流群285154486,每天會講解分享項目,答疑解惑。