中心细胞网格布局
问题描述:
内容我有一个网格布局面板(1,3),但我想集中细胞在此布局的内容(不加面板):中心细胞网格布局
public MainMenu() {
setLayout(new GridLayout(1, 3));
setBorder(BorderFactory.createLineBorder(Color.BLUE));
setOpaque(false);
ImageComponent img = new ImageComponent("resources/music.png", true, this);
add(img);
ImageComponent img1 = new ImageComponent("resources/video.png", true, this);
add(img1);
ImageComponent img2 = new ImageComponent("resources/audio", true, this);
add(img2);
}
,因为如果我只添加这3 ImageComponents到MainMenu它们向上出现。
答
GridLayout将调整所有组件的大小以填充可用空间。因此,如果您的3个ImageComponents的尺寸是50x50,50x50和75x75,则它们的尺寸均为75x75。从那里它取决于ImageComponent如何绘制自己。
最有可能实现ImageComponent的paintComponent是这样的:
protected void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, this);
}
这将在左上角,不居中绘制图像。
这将画一个居中的图像:
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
int iw = image.getWidth(this);
int ih = image.getHeight(this);
if (iw != -1 && ih != -1)
{
int w = getWidth();
int h = getHeight();
g.drawImage(image, (w -iw)/2, (h-ih)/2, this);
}
}
感谢德文!你是最棒的)))) – 2010-07-16 20:39:32