首页 > 技术文章 > JavaGUI——设置框架背景颜色和按钮颜色

zpcdbky 2015-05-05 00:35 原文

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还是实际测试,都可以验证:两者是一样的。

推荐阅读