20

如何使 JPanel 可滚动?当我将它添加到包含面板时,我实现了可滚动界面

tabbedPane.add("Editor", new JScrollPane(storeyEditor = new MNScrollablePanel()));

没有任何作用

代码:

public class MNScrollablePanel extends JPanel implements Scrollable {

    public Dimension getPreferredScrollableViewportSize() {
        return getPreferredSize();
    }

    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 10;
    }

    public boolean getScrollableTracksViewportHeight() {
        return false;
    }

    public boolean getScrollableTracksViewportWidth() {
        return false;
    }

    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        return 10;
    }
}
4

5 回答 5

30

它像这样和我一起工作......

JPanel test = new JPanel();
test.setPreferredSize(new Dimension( 2000,2000));
JScrollPane scrollFrame = new JScrollPane(test);
test.setAutoscrolls(true);
scrollFrame.setPreferredSize(new Dimension( 800,300));
this.add(scrollFrame);
于 2011-07-05T11:42:32.667 回答
12

你必须使用一个JScrollPane. 然后调用setViewportview(Component);

您不必实现可滚动,JPanel 已经可以滚动

于 2009-09-06T14:02:47.927 回答
1

正如所有其他帖子中提到的,没有理由自己实现 Scrollable 接口。但是,如果您只是在玩,那么发布的基本代码看起来很合理。但是,您没有发布演示程序来展示您如何使用此代码。将来,请在 SSCCE 上发布您的问题。如果您不知道 SSCCE 是什么,请在网上搜索。

曾经可能出现的问题是,当添加到滚动窗格视口的组件的“首选大小”大于滚动窗格的大小时,滚动条会自动出现。

因此,如果您在面板上进行自定义绘画,您有责任在面板更改时设置面板的首选尺寸。如果您正在使用带有组件和布局管理器的面板,那么您不必担心这一点。但是,如果您使用带有空布局管理器的组件,您也会遇到问题。

这就是我们需要 SSCCE 的原因,因为我们不知道您如何使用该面板的上下文。

于 2009-09-06T15:02:52.017 回答
1

JPanel 没有实现 Scrollable。最好使用SwingX中的 JXPanel ,它实现了 Scrollable 并具有更多功能。

于 2012-05-30T11:33:52.070 回答
0

我有一个新的解决方案给你。

我认为您必须使用以下代码:

storyEditor = new JPanel();
storyEditor.setPreferredSize(new Dimension(..., ...)); // Insert Here your size for the editor
JScrollPane scroller = new JScrollPane(storyEditor);
tabbedPane.add("Editor", scroller));
frame.setSize(frame.getWidth()+1, frame.getHeight()); // frame is the JFrame where the tabbed pane is into
// Maybe you can replace "frame" with "this"
// You need to resize your frame. Why, I don't know...
frame.pack();
// Your original size will be restored by calling pack

这对我来说是一个解决方案。我希望你能!

于 2009-09-14T18:16:31.067 回答