Java GUI设计第4篇:混用多种布局管理器

时间:2024-05-20 21:24:39

在上一篇文章中,我们的每一个程序都只使用了一种布局管理器。但是在实际的程序中,界面往往会比较复杂。如果只用无布局管理器,那么我们的窗口在调整大小之后就难以对组件的位置进行控制。

在Java程序中,可以使用多种布局管理器,我们只需要借助一种组件,叫做JPanel,它是一种不可见的容器。在JFrame中,可以添加JPanel,JPanel本身也可以添加组件,设置布局管理器等。

我们可以看看以下程序的运行效果:

package teach4;

import java.awt.GridLayout;

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

public class MF1 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel p[]=new JPanel[4];
	public MF1() {
		this.setSize(400, 300);
		this.setLocationRelativeTo(null);//将窗口的位置设置在正中间
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new GridLayout(2,2));
		for(int i=0; i<4; i++) {
			p[i]=new JPanel();
			this.add(p[i]);
		}
	}
	public static void main(String[] args) {
		MF1 mf=new MF1();
		mf.setVisible(true);
	}
}

效果:

Java GUI设计第4篇:混用多种布局管理器

可以看见,JPanel是一种不可见的组件,里面是一片空白。

假如我们需要多种布局管理器,我们可以将组件放在不同的JPanel对象中,JPanel也有setLayout()的方法。

比如我们修改上述的代码,我们将p[2]的布局方法设置为FlowLayout,然后向其中添加5个按扭。

package teach4;

import java.awt.FlowLayout;
import java.awt.GridLayout;

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

public class MF1 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel p[]=new JPanel[4];
	JButton b[]=new JButton[5];
	public MF1() {
		this.setSize(400, 300);
		this.setLocationRelativeTo(null);//将窗口的位置设置在正中间
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new GridLayout(2,2));
		for(int i=0; i<4; i++) {
			p[i]=new JPanel();
			this.add(p[i]);
		}
		p[2].setLayout(new FlowLayout());//JPanel也可以setLayout
		for(int i=0; i<5; i++) {
			b[i]=new JButton("Java");
			p[2].add(b[i]);//注意要在p[2]中添加,而不是this
		}
	}
	public static void main(String[] args) {
		MF1 mf=new MF1();
		mf.setVisible(true);
	}
}

效果:

Java GUI设计第4篇:混用多种布局管理器

在窗口大小改变时,仍然可以调整位置:

Java GUI设计第4篇:混用多种布局管理器

接下来,我们需要设计一个窗口,其中包含两个JPanel,一个在上方,另一个在下方。上方的这个用FlowLayout,有3个按扭,下方的这个用GridLayout,2*2,并有一定间隔:

package teach4;

import java.awt.FlowLayout;
import java.awt.GridLayout;

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

public class MF2 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	JPanel p[]=new JPanel[2];
	JButton b1[]=new JButton[5];
	JButton b2[]=new JButton[4];
	public MF2() {
		this.setSize(400, 600);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setLayout(new GridLayout(2,1));
		for(int i=0; i<2; i++) {
			p[i]=new JPanel();
			this.add(p[i]);
		}
		p[0].setLayout(new FlowLayout());
		for(int i=0; i<5; i++) {
			b1[i]=new JButton("Java1");
			p[0].add(b1[i]);
		}
		p[1].setLayout(new GridLayout(2,2,5,5));
		for(int i=0; i<4; i++) {
			b2[i]=new JButton("Java2");
			p[1].add(b2[i]);
		}
	}
	public static void main(String[] args) {
		MF2 mf=new MF2();
		mf.setVisible(true);
	}
}

效果:

Java GUI设计第4篇:混用多种布局管理器

这样,我们就实现了使用多种布局管理器的窗口。