zoukankan      html  css  js  c++  java
  • 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还是实际测试,都可以验证:两者是一样的。

  • 相关阅读:
    一个完整的Http请求
    struts2回显指定的错误信息
    Struts2中的OGNL通配符
    hibernate日常BUG总结
    Hibernate中的GetCurrentSession()方法
    hibernate query.list() 返回的数据类型
    xp远程桌面登陆需要身份验证问题解决
    spring和hibernate整合时无法自动建表
    Spring的scope="prototype"属性
    给程序员的九点建议
  • 原文地址:https://www.cnblogs.com/zpcdbky/p/4478089.html
Copyright © 2011-2022 走看看