布局管理器

 

                   布局管理器

  • 布局管理器可通过调用setLayout()改变。

1、FlowLayout 流式布局管理器 2、BorderLayout 边界布局管理器 3、GirdLayout 网格布局管理器 4、CardLayout 卡片布局管理器 5、GirdBayLayout 网格包布局管理器 6、BoxLayout 箱式布局管理器 7、无布局

流式布局(flowlayout)

  • align的取值为FlowLayout.LEFT(左)、FlowLayout.RIGHT(右)、FlowLayout.CENTER(中间)。

package src1;

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Prectice2 extends JFrame
{
JPanel jPanel;
JButton but1,but2,but3,but4;
FlowLayout flowLayout;

  public Prectice2(String prectice)
  {
  super(prectice);
init();
  }
public void init( )
{
jPanel=new JPanel();
flowLayout=new FlowLayout(flowLayout.LEFT,24,33);//(左)
// flowLayout=new FlowLayout(flowLayout.RIGHT,24,33);//(右)
// flowLayout=new FlowLayout(flowLayout.CENTER,24,33);//(中)
but1=new JButton("按钮1");
but2=new JButton("按钮2");
but3=new JButton("按钮3");
but4=new JButton("按钮4");
jPanel.add(but1);
jPanel.add(but2);
jPanel.add(but3);
jPanel.add(but4);
jPanel.setLayout(flowLayout);
this.setContentPane(jPanel);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setSize(300,200);
this.setResizable(true);
}  



  public static void main(String[] args)
  {
Prectice2 prectice2=new Prectice2("prectice");
  }
}

 

                   无布局管理器

  • 要采用无布局管理器布局,首先要取消Swing默认的布局管理器,否则布局方法不会生效

  • 方法是调用容器的setLayout方法,并将布局管理器设置为null。取消默认的布局管理器之后,就可以使用GUI组件的setLocation()、setSize()、setBounds()等布局方法来对GUI组件的位置、大小进行设置。

  • 方法 :setBounds(int x, int y, int width, int height)

package src1;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Prectice3 extends JFrame
{
JPanel jPanel;
JButton but1,but2;
JLabel lab1,lab2;
JTextField text1,text2;
public Prectice3(String prectice)
{
super(prectice);
init();
}
public void init()
{
  jPanel=new JPanel(null);//无布局
 //p.setLayout(null);//无布局
  but1=new JButton("登录");
  but2=new JButton("关闭");
   lab1=new JLabel("账号");
  lab2=new JLabel("密码");
  text1=new JTextField(15);
  text2=new JTextField(15);
 
  jPanel.add(lab1);
  lab1.setBounds(10, 10, 65, 15);
  jPanel.add(lab2);
  lab2.setBounds(10, 35, 65, 15);
  jPanel.add(text1);
  text1.setBounds(75, 8, 170, 20);
  jPanel.add(text2);
  text2.setBounds(75, 33, 170, 20);
jPanel.add(but1);
but1.setBounds(60, 70, 60, 40);
  jPanel.add(but2);
  but2.setBounds(150, 70, 60, 40);
  this.setContentPane(jPanel);
  this.setSize(300,250);
  this.setVisible(true);
  this.setLocationRelativeTo(null);
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);
  this.setResizable(true);
}
   public static void main(String[] args)
  {
Prectice3 prectice3=new Prectice3("无布局");
}
}
 
posted @ 2022-05-08 23:18  zjw_rp  阅读(210)  评论(0编辑  收藏  举报