可滚动的JPanel
如何使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; } }
您必须使用JScrollPane
。 然后调用setViewportview(Component)
;
您不必实现可滚动,JPanel已经可以滚动
它和我一起工作….
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);
正如所有其他post中所提到的,没有理由自己实现Scrollable接口。 但是,如果您只是玩游戏,那么发布的基本代码看起来很合理。 但是,您没有发布演示程序,显示您如何使用此代码。 将来,在您的问题上发布SSCCE。 如果您不知道SSCCE是什么,那么搜索网络。
一旦可能的问题是当添加到滚动窗格的视口的组件的“首选大小”大于滚动窗格的大小时,滚动条会自动出现。
因此,如果您在面板上进行自定义绘制,则您需要在更改时设置面板的首选大小。 如果您使用的是带有组件和布局管理器的面板,那么您不必担心这一点。 但是,如果您使用带有null布局管理器的组件,那么您也会遇到问题。
这就是我们需要SSCCE的原因,因为我们不知道您如何使用该面板的背景。
JPanel不实现Scrollable。 最好使用SwingX的 JXPanel,它实现了Scrollable并具有更多function。
我有一个新的解决方案。
我想你必须使用这段代码:
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
这对我来说是一个解决方案。 我希望你能来!