java swing 之绝对布局

来源:互联网 发布:燃气灶烤箱一体机 知乎 编辑:程序博客网 时间:2024/05/19 13:22
Swing 中窗体具有默认的布局管理器,如JFrame 使用是边界布局。虽然布局管理器能够简化程序的开发,但是为了获取最大的灵活性,可以使用绝对布局,即不使用任何布局管理器,是哦那个该布局的步骤如下:

(1) 使用Container.setLayout(null)方式取消布局管理器。

(2)使用Component.setBounds()方法来设置每个控件的大小与位置。

/** * java 图形界面之绝对布局 * @author gao */package com.gao;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;public class AbsoluteLayoutDemo extends JFrame {   private JPanel contentPane;//创建面板   private JButton button1;//创建按钮1   private JButton button2;//创建按钮2   public AbsoluteLayoutDemo()   {   this.setTitle("绝对布局");//设置标题名字   this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//默认退出   this.setBounds(100, 100, 250, 100);//设置窗体的大小   this.contentPane=new JPanel();//初始化面板   this.contentPane.setLayout(null);//设置布局NULL   this.button1=new JButton("按钮1");//给按钮名字   this.button1.setBounds(6,6,90,30);//设置按钮名字   this.contentPane.add(button1);//加入面板中   this.button2=new JButton("按钮2");   this.contentPane.add(button2);   this.button2.setBounds(138, 26, 90, 30);   this.add(this.contentPane);   this.setVisible(true);      }   public static void main(String[]args)   { AbsoluteLayoutDemo example=new AbsoluteLayoutDemo();   }}


0 0
原创粉丝点击