簡體   English   中英

如何獲得版式中的可用空間?

[英]How can I get the space avaiable in a Layout?

我有這個分布的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);

問題是我找不到可用空間的大小(對於BorderLayout.CENTER)。 我在代碼中寫了窗口大小,但是那是不正確的,我也嘗試過:

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

但它也給出了不正確的值,或者至少沒有給出我要查找的值。 而且我找不到其他與尺寸有關的方法。 並且嘗試從將要存在的面板中獲取值是不可行的,因為在創建它之前我需要該值。

誰能告訴我如何找到這個價值? 謝謝。

您不應該嘗試獲取可用的大小。

如果您真的想知道此值,則應該進行自定義繪制並動態調整圖像的大小,然后在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教程中有關如何編寫組件偵聽器的部分, 獲取更多信息和示例。

最后,您還可以使用Darryl的“ 拉伸圖標” ,該圖標會根據可用空間自動縮放圖標。 您需要做的就是使用StretchIcon創建一個JLabel並將其添加到您的GUI中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM