我需要设置 JPanel 的首选大小,以便 JFrame 组件的 pack() 方法正常工作。如何自动设置此尺寸?我有一个带有 GridLayout 3x3 的 JPanel,里面装满了 9 个 ImagePanel:
public class ImagePanel extends JPanel {
private Image image;
public ImagePanel(Image image) {
this.image = image;
setSize(image.getWidth(null), image.getHeight(null));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
现在我想做的是获取这个 JPanel 图像的大小。
image.getWidth() * 3
image.getHeight() * 3
不是我想要的。我宁愿想知道类似于 pack() 的东西。
最佳答案
最简单的方法是让图像确定组件的首选大小,如下所示:
public class ImagePanel extends JPanel {
private Image image;
public ImagePanel(Image image) {
this.image = image;
// setSize(image.getWidth(null), image.getHeight(null));
}
@Override
public Dimension getPreferredSize() {
if (image != null) {
int w = image.getWidth();
int h = image.getHeight();
return new Dimension(w, h);
} else {
return super.getPreferredSize();
}
}
@Override // this should be protected, not public
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
}
关于java - 根据内容调整框架大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367943/