有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在布局中获得可用空间?

我有一个带有此发行版的borderLayout: enter image description here

在红色的位置,我想把一个图像缩放,使其填补所有可用的空间。此外,我还可以选择以真实图像的不同比例(20%、50%、100%)显示图像

我试图找到使图像完美匹配的比例因子:

    //GET VALUES
    int imageWidth = image1.getWidth();
    int imageHeight = image1.getHeight();
    System.out.println("Image: "+imageWidth + " "+ imageHeight);
    int targetWidth = this.getBounds().width;
    int targetHeight = this.getBounds().height;
    System.out.println("Target: " + targetWidth + " "+ targetHeight);

    //GET SCALE
    float scaleWidth=1;
    float scaleHeight=1;
    if (imageWidth > targetWidth) {
        scaleWidth = (float) targetWidth  / (float) imageWidth;
     }
    if (imageHeight > targetHeight) {
        scaleHeight = (float) targetHeight / (float) imageHeight;
     } 

    return min(scaleWidth, scaleHeight);

问题是我找不到可用空间的大小(对于BorderLayout.CENTER)。我在代码中写入了窗口大小,但这是不正确的,我还尝试了:

 this.getLayout().preferredLayoutSize(this).width; 

但它也给出了一个不正确的值,或者至少不是我想要找到的。我找不到其他与尺寸相关的方法。试图从即将出现的面板中获取价值是不可行的,因为我需要在创建它之前获得价值

谁能告诉我怎么才能找到这个值? 多谢各位


共 (1) 个答案

  1. # 1 楼答案

    您不应该试图获得可用的尺寸

    如果你真的想知道这个值,那么你应该进行自定义绘制,动态调整图像大小,并用paintComponent()方法绘制图像

    所以基本代码是这样的:

    public class ImagePanel extend JPanel
    {
        public ImagePane(...)
        {
        }
    
        @Override
        protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
    
            int width = getWidth();
            int height = getHeight();
    
            // do your scaling
    
            g.drawImage(...);
        }
    }
    

    或者,如果不想进行动态缩放,则可以向面板中添加ComponentListener并处理componentResized事件。然后你可以得到面板的真实尺寸,并进行缩放计算。阅读Swing教程中关于How to Write a Component Listener的部分,了解更多信息和示例

    最后,您还可以使用Darryl的Stretch Icon,它将根据可用空间自动缩放图标。你所需要做的就是使用StretchIcon创建一个JLabel并将其添加到你的GUI中