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無論設置成什么顏色,都將被頂層面板所覆蓋。因此,要改變背景顏色,就要改變面板的背景顏色。

另外,Color中的顏色(如GREEN,RED)都有大寫和小寫兩種形式,無論是查閱API還是實際測試,都可以驗證:兩者是一樣的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM