IT干货网

Panel类

xmjava 2022年03月12日 编程设计 206 0

Panel类

一般我们会在Frame界面中放入Panel面板,以下代码演示了这一过程:

package com.cxf.gui; 
 
import java.awt.*; 
 
public class Demo3 { 
    public static void main(String[] args) { 
 
        Panel panel = new Panel(); 
        Frame frame = new Frame(); 
 
        panel.setVisible(true); 
        frame.setVisible(true); 
 
        panel.setBackground(Color.red); 
        frame.setBackground(Color.orange); 
 
        panel.setBounds(50,50,400,400); 
        frame.setBounds(400,400,500,500); 
 
        frame.setLayout(null); 
 
        frame.add(panel); 
 
    } 
} 
 

输出结果:

上述代码分别设置panel(红色)和frame(黄色)的参数,再用add把他们连接。

第20行的setlayout设置布局,如果不使用此语句,把它注释掉,即

package com.cxf.gui; 
 
import java.awt.*; 
 
public class Demo3 { 
    public static void main(String[] args) { 
 
        Panel panel = new Panel(); 
        Frame frame = new Frame(); 
 
        panel.setVisible(true); 
        frame.setVisible(true); 
 
        panel.setBackground(Color.red); 
        frame.setBackground(Color.orange); 
 
        panel.setBounds(50,50,400,400); 
        frame.setBounds(400,400,500,500); 
 
        //frame.setLayout(null); 
 
        frame.add(panel); 
 
    } 
} 

那么输出结果会变为:

panel(红色)铺满了frame,这是默认布局,显然不是我们想要的结果,因此第20行setlayout(null)不可缺少,它清空了默认布局。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!