在 GridBagLayout 中控制 ScrollPane 的缩小行为

Controlling downsize behaviour of ScrollPane within GridBagLayout

我正在尝试在 GUI 中处理图像。我需要在 GUI 中显示一个图像,周围有几个其他组件。如果调整 GUI window 的大小,只有图像区域需要随之调整大小。

我认为使用 GridBagLayout 是可行的方法,但是当我这样做时,持有图像的 ScrollPane 的调整大小行为是出乎意料的:当 GUI window 是以可用 space 对于 ScrollPane 中的图像来说太小的方式缩小尺寸,ScrollPane 组件立即缩小到比可用 space 小得多的尺寸.

代码示例图片:qm.png

import scala.swing.{ Button, GridBagPanel, Label, MainFrame, ScrollPane, SimpleSwingApplication }
import javax.swing.ImageIcon

object GridBag_vs_ScrollPane extends SimpleSwingApplication {
    def top = new MainFrame {
        title = "GridBag vs ScrollPane"
        contents = gui
    }

    val gui = new GridBagPanel {
        val fp_img = """.\resources\qm.png"""
        val scrPane = new ScrollPane( new Label { icon = new ImageIcon(fp_img) } )
        val button1 = new Button("Button 1")

        val c = new Constraints
        c.gridx = 0
        c.gridy = 0
        layout(button1) = c

        c.weighty = 1.0
        c.gridx = 0
        c.gridy = 1
        layout(scrPane) = c
    }
}

我正在寻找的 ScrollPane 的行为更像是下一段代码的行为:

import javax.swing.ImageIcon

import scala.swing.{Label, MainFrame, ScrollPane, SimpleSwingApplication}

object SimpleScrollPane extends SimpleSwingApplication {
    def top = new MainFrame {
        title = "Simple ScrollPane"
        val fp_img = """.\resources\qm.png"""
        contents = new ScrollPane( new Label { icon = new ImageIcon(fp_img) } )
    }
}

我不知道如何获得所需的行为,也不知道为什么 ScrollPane 在两个 GUI 实现中的行为不同。

谁能教教我?

在您添加到滚动窗格的组件中,覆盖

public Dimension getMinimumSize() 

public Dimension getPreferredSize()

不同的布局管理器使用这些值。

Andrew Thompson的建议让我半途而废。我需要将 c.fill = Fill.Bothc.weightx = 1.0 添加到滚动窗格的约束中。

填充约束是解决方案的一部分这一事实对我来说是违反直觉的,因为 tutorial on GridBagLayout 将填充约束描述为 «当组件的显示区域大于组件请求的大小时使用,以确定是否以及如何调整组件大小。»,而在我的例子中,滚动窗格组件的请求大小实际上大于可用显示区域。