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

  • 相关阅读:
    对我影响最大的老师
    介绍自己
    JavaScript 时间特效 显示当前时间
    js 获取函数的所有参数名
    node.js 在函数内获取当前函数
    js 实现二叉排序树
    命令行下mysql的部分操作
    浅析js的函数的按值传递参数
    返回上一页时,保存恢复浏览记录(模拟返回不刷新)
    让mongodb执行js文件
  • 原文地址:https://www.cnblogs.com/zpcdbky/p/4478089.html
Copyright © 2011-2022 走看看