如何自定義居中佈局

需求:需要將一個組件顯示在界面的正中間部分,並且可以調節居中組件所佔整個界面的百分比

分析:由於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));
	}
}	


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章