JavaGUI——設置框架背景顏色和按鈕顏色

import java.awt.Color;
import javax.swing.*;

public class MyDraw 
{

    public static void main(String[] args) 
    {
        //建立框架
        JFrame myFrame=new JFrame("圖畫");
        //myFrame.setLocation(200, 300);//第1參數表示離左屏幕邊框距離,第2參數表示離屏幕上邊框距離
        myFrame.setSize(600, 400);
        myFrame.setResizable(true);
        myFrame.setDefaultCloseOperation(3);
        //建立按鈕
        JButton blackButton,whiltButton,otherButton;
        blackButton=new JButton("黑色");
        whiltButton=new JButton("白色");
        otherButton=new JButton("自定義");
        //設置背景顏色、按鈕顏色
        JPanel jp=new JPanel();
        jp.add(blackButton);
        jp.add(whiltButton);
        jp.add(otherButton);
        myFrame.add(jp);
        jp.setBackground(Color.GREEN);
        blackButton.setForeground(Color.BLACK);
        whiltButton.setForeground(Color.YELLOW);
        otherButton.setForeground(Color.BLUE);
        myFrame.setVisible(true);
    }
}

方法淺釋:
將按鈕添加到面板,再將面板添加到框架中,要經過面板來調用setBackground()方法來設置框架的背景顏色,直接使用myFrame.setBackground(Color.GREEN);是不會起做用的。緣由是JFrame一旦建立,其中已包含一個內容面板,此時myFrame.setBackground不管設置成什麼顏色,都將被頂層面板所覆蓋。所以,要改變背景顏色,就要改變面板的背景顏色。
java

另外,Color中的顏色(如GREEN,RED)都有大寫和小寫兩種形式,不管是查閱API仍是實際測試,均可以驗證:二者是同樣的。框架

相關文章
相關標籤/搜索