0

我正在构建一个处理截屏的小型 Java 应用程序。我有一个从 JPanel 继承的自定义类,称为 ScreenshotPanel,它保存图像,它位于 JScrollPane 内。调整框架大小时,ScrollPane 会移动并调整大小。除了缩放部分,一切都很好,我希望能够控制 ScrollPane 内 screenshotPanel 的大小,但是 screenshotPanel 不会调整大小,它会以正确的大小闪烁片刻,但随后会调整回 ScrollPane 的大小尺寸。

如果我在没有 ScrollPane 的情况下使用 screenshotPanel,它可以完全正确地工作,但我希望它自动添加滚动条,以便您可以在放大时看到移动图像。

这是我用来调整大小的部分代码:

    double AR=((double)screenshotPanel.getImage().getHeight())/screenshotPanel.getImage().getWidth();

    screenshotPanel.setSize((int)((getWidth()-180)*zoomFactor), (int)((AR*(getWidth()-180)-100)*zoomFactor));
    scrollPane.setSize(getWidth()-180, (int)(AR*(getWidth()-180))-100);

-180 和 -100 用于为按钮和缩放控制组件保留空间(它们都可以完美地移动和调整大小),zoomFactor 是保存缩放量的双倍。

如何调整 ScrollPane 内的 screenshotPanel 的大小,而 ScrollPane 不强制它的大小变回?

4

1 回答 1

1

Changing the size of the component won't scale the image, unless you have code in your paint method to compensate for the change in size.

JViewPort is respecting your components preferred size, thus you get this flicker, as you change the size and the viewport resets it.

Add a scale method to your panel and override the getPreferredSize method.

When you call setScale, calculate the new scaled size. Make sure that the getPreferredSize method returns these values.

You will need to call invalidate and possibly repaint to make sure the change is updated through the container hierarchy.

Remember, the pane will not resize the image on it's own, you are responsible for taking this ;)

于 2012-11-02T20:44:21.793 回答