package util;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CenterPanel extends JPanel {
private double rate;//拉伸比例
private JComponent c; //显示的组件
private boolean strech; //是否拉伸
public CenterPanel(double rate,boolean strech) {
this.setLayout(null);
this.rate = rate;
this.strech = strech;
}
public CenterPanel(double rate) {
this(rate,true);
}
public void repaint() {
if (null != c) {
Dimension containerSize = this.getSize();//容器尺寸
Dimension componentSize= c.getPreferredSize();//元素尺寸
if(strech)
c.setSize((int) (containerSize.width * rate), (int) (containerSize.height * rate));//需要拉伸,将组件尺寸设置为容器尺寸*拉伸率
else
c.setSize(componentSize);
c.setLocation(containerSize.width / 2 - c.getSize().width / 2, containerSize.height / 2 - c.getSize().height / 2);//设置为中央位置
}
super.repaint();
}
//使用show方法显示组件,show方法中的思路是: 先把这个容器中的组件都移出,然后把新的组件加进来,并且调用updateUI进行界面渲染。
//updateUI会导致swing去调用repaint()方法。
public void show(JComponent p) {
this.c = p;
Component[] cs = getComponents();
for (Component c : cs) {
remove(c);
}
add(p);
this.updateUI();//调用repaint方法
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setSize(200, 200);
f.setLocationRelativeTo(null);
CenterPanel cp = new CenterPanel(0.85,true);
f.setContentPane(cp);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
JButton b =new JButton("abc");
cp.show(b);
}
}