java窗口背景颜色的设定----setBackground()的用法:
办法一:

在完成初始化,调用getContentPane()方法得到一个contentPane容器,然后将其设置为不可见,即setVisible(false)。

import javax.swing.*;
import java.awt.*
public class TestMenuBar1 {
    public static void main(String arg[]) {
        createNewMenu ck=new createNewMenu("第一个窗口");
    }
}
class createNewMenu extends JFrame{
    public createNewMenu(String title) {
        getContentPane().setVisible(false);
        setBackground(Color.blue);  //设置窗口背景颜色
        setTitle(title);
        setBounds(200,200,500,500); //设置窗口位置和大小
        setVisible(true);  //设置窗口可见
    }
}

办法二:

直接加 this.getContentPane().setBackground(Color.blue);

import java.awt.*;
import javax.swing.*;
public class TestMenuBar1 {
    public static void main(String arg[]) {
        createNewMenu ck=new createNewMenu("第一个窗口");
    }
}
class createNewMenu extends JFrame{
    public createNewMenu(String title) {
        setTitle(title);
        setBounds(200,200,500,500);
        setVisible(true);
        this.getContentPane().setBackground(Color.blue);
    }
}

 实战操作:

package com.company;

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

public class Test1
{
    public static void main(String[] args)
    {
        JFrame f = new JFrame("第一个Swing窗体");    //实力化窗体对象;
        f.setSize(230,80);                 //设置窗体大小:public void setSize(int width,int height);
        f.getContentPane().setBackground(Color.RED);      //设置窗体的背景颜色:public void setBackground(Color c);
        f.setLocation(300,200);                    //设置窗体的显示位置:public void setLocation(int x,int y);
        f.setVisible(true);                               //显示或隐藏组件:public void setVisible(boolean b);[true:显示组件  false:隐藏组件]
    }
}

运行结果:

 绝对布局

绝对布局,顾名思义,就是硬性指定组件在容器中的位置和大小,可以使用绝对坐标的方式来指定组件的位置。
使用绝对布局的步骤如下:

使用Container.setLayout(null)方法取消布局管理器。
使用Component.setBounds()方法设置每个组件的大小与位置

流布局管理器

流布局管理器在整个容器中的布局正如其名,像“流”一样从左到右摆放组件,直到占据了这一行的所有空间,然后再向下移动一行。默认情况下,组件在每一行上都是居中排列的,但是通过设置也可以更改组件在每一行上的排列位置。
FlowLayout类中具有以下常用的构造方法:

public FlowLayout()
public FlowLayout(int alignment)
public FlowLayout(int alignment, int horizGap, int vertGap

流布局管理器

流布局管理器在整个容器中的布局正如其名,像“流”一样从左到右摆放组件,直到占据了这一行的所有空间,然后再向下移动一行。默认情况下,组件在每一行上都是居中排列的,但是通过设置也可以更改组件在每一行上的排列位置。
FlowLayout类中具有以下常用的构造方法:

public FlowLayout()
public FlowLayout(int alignment)
public FlowLayout(int alignment, int horizGap, int vertGap)

构造方法中的alignment参数表示使用流布局管理器后组件在每一行的具体摆放位置。alignment为0时,每一行的组件将被指定按照左对齐排列;alignment为2时,每一行的组件将被指定按照右对齐排列;alignment为1时,每一行的组件将被指定按照居中对齐排列;
horizGap与vertGap参数分别以像素为单位指定组件之间的水平间距与垂直间距。

 

边界布局管理器
在默认不指定窗体布局的情况下,Swing组件的布局模式是BorderLayout布局管理器。边界布局管理器可以将容器划分为东、南、西、北、中5个区域,可以将组件加入到这5个区域中。容器调用Container类的add()方法添加组件时可以设置此组件在边界布局管理器中的区域,区域的控制可以由BorderLayout类中的成员变量来决定

 

 

 

posted on 2019-11-08 20:46  青春永驻岁月无忧  阅读(158)  评论(0编辑  收藏  举报