Java API 分類導覽 - java.awt.Component setBackground()

Component 類別 (class) 的 setBackground() 方法 (method) 用來設定視窗或元件的背景顏色。



修飾子與參數
public void setBackground(Color c)


setBackground() 沒有回傳值 (return value) ,需要提供 Color 型態 (type) 的物件 (object) 當參數 (paramenter) 。


舉例如下
import java.awt.*;
import java.awt.event.*;

public class getBackgroundDemo {
    public static void main(String[] args) {
        Frame frame = new Frame("AWTDemo");
        frame.addWindowListener(new AdapterDemo());
        frame.setForeground(Color.white);
        frame.setBackground(Color.blue);
        
        Label a1 = new Label("a1");
        Label a2 = new Label("a2");
        
        frame.setLayout(new FlowLayout());
        frame.add(a1);
        frame.add(a2);
        
        frame.pack();
        frame.setVisible(true);
        
        System.out.println("Foreground: " + frame.getForeground());
        System.out.println("Background: " + frame.getBackground());
    }
}

class AdapterDemo extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
}

/* 《程式語言教學誌》的範例程式
    http://pydoing.blogspot.com/
    檔名:getBackgroundDemo.java
    功能:示範 Java 程式 
    作者:張凱慶
    時間:西元 2012 年 3 月 */


此例建立視窗後,呼叫 Component 的 setForeground() ,將前景顏色設定為 Color.white ,也就是白色
frame.setForeground(Color.white);


然後呼叫 Component 的 setBackground() ,將背景顏色設定為 Color.blue ,也就是藍色
frame.setBackground(Color.blue);


接著建立兩個 Label ,加入視窗之中
Label a1 = new Label("a1");
Label a2 = new Label("a2");
        
frame.setLayout(new FlowLayout());
frame.add(a1);
frame.add(a2);


最後在命令列利用 Component 的 getForeground() 與 getBackground() 印出前景與背景顏色值
System.out.println("Foreground: " + frame.getForeground());
System.out.println("Background: " + frame.getBackground());


編譯後執行,結果如下



中英文術語對照
類別class
方法method
回傳值return value
型態type
物件object
參數parameter


您可以繼續參考
AWT 元件


相關目錄
Java API 分類導覽
Java 教材
首頁


參考資料
http://docs.oracle.com/javase/6/docs/api/java/awt/Component.html

沒有留言: