如何自定义居中布局

需求:需要将一个组件显示在界面的正中间部分,并且可以调节居中组件所占整个界面的百分比

分析:由于Java提供的布局管理器并不能提供上诉需求,故需要自己来实现

先上效果图(占据50%)


代码部分

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MyCenterPanel extends JPanel
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Double rate;  //要显示的组件居中占据的百分比
	private JComponent c;  //最终要显示的JComponent
	
	//设置构造函数
	public MyCenterPanel(Double rate)
	{
		this.setLayout(null);
		this.rate = rate;
	}

	
	//设置要显示的组件
	public void show(JComponent p)
	{
		this.c = p;
		this.add(c);
		this.updateUI(); 
		this.updateUI(); //有时候执行一次updateUI()方法不能显示出JLabel,所以此处我执行了两遍
	}
	
	public void repaint()	//设置要显示组件的排放位置
	{
		if(c != null)
		{
			Dimension cp_size = this.getSize();		
			c.setSize((int)(cp_size.width*rate),(int)(cp_size.height*rate));
			c.setLocation(cp_size.width / 2 - c.getWidth() / 2, cp_size.height / 2 - c.getHeight() / 2);
		}
	}
	
	public static void main(String[] args)
	{
		JFrame f = new JFrame();
		f.setVisible(true);
		f.setSize(1000, 600);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setLocationRelativeTo(null);
		MyCenterPanel mcp = new MyCenterPanel(0.5);
		f.setContentPane(mcp);
		JLabel label = new JLabel("我是JLabel",JLabel.CENTER);
		mcp.show(label);
		label.setBorder(BorderFactory.createLineBorder(Color.RED));
	}
}	


猜你喜欢

转载自blog.csdn.net/maty_wang/article/details/79156731