【问题标题】:How can I get the space avaiable in a Layout?如何获得布局中的可用空间?
【发布时间】:2016-11-03 13:56:40
【问题描述】:

我有一个带有这种分布的borderLayout:

我想在红色位置放置一个缩放的图像,以便它填充所有可用空间。我还可以选择以不同比例显示真实图像(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);

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

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

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

谁能告诉我如何找到这个值? 谢谢。

【问题讨论】:

  • 您忘记指定您正在使用的框架。好像你在使用 AWT/swing?
  • @PEMapModder 是的,抱歉,我刚刚添加了它。

标签: java swing layout scaling space


【解决方案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 事件。然后您可以获得面板的实际尺寸并进行缩放计算。阅读 How to Write a Component Listener 上的 Swing 教程部分,了解更多信息和示例。

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

【讨论】:

    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多