JScrollPane with fixed width

前端 未结 1 1369
独厮守ぢ
独厮守ぢ 2020-12-18 08:13

I am newbie in Java Swing and I am confused about next code.

My goal is make vertical scrollable panel with 2 JTextPane(s) inside i

相关标签:
1条回答
  • 2020-12-18 08:37

    The problem is that a scrollpane will display a component at its preferred size and then add scroll bars as required.

    In your case you want the width to be constrained by the viewport of the scrollpane.

    So therefore you need to implement the Scrollable interface on the component you add to the viewport. The Scrollable interface will allow you to force the component width to match the width of the viewport which in turn will limit the width of each JTextPane causing the text to wrap.

    An easy way to implement this functionality is to use the Scrollable Panel. This class implements the Scrollable interface and allows you to override the Scrollable methods by using parameters.

    So the basic code would be:

    ScrollablePanel panel = new ScrollablePanel( new BorderLayout());
    panel.setScrollableWidth( ScrollablePanel.ScrollableSizeHint.FIT );
    

    The first JTextPane with fixed width 70 % of parent panel and the second JTextPane with fixed width 30 %

    One way to do this might be to use a JSplitPane so you have a divider between the two text panes and the text doesn't merge into one.

    JSplitPane splitPane = new JSplitPane();
    splitPane.setLeftComponent(new JTextPane());
    splitPane.setRightComponent(new JTextPane());
    splitPane.setResizeWeight(0.7);
    splitPane.setDividerLocation(.7);
    

    Then you just add everything to the frame:

    panel.add(splitPane);
    frame.add(new JScrollPane(panel), BorderLayout.CENTER);
    

    Now the divider location will remain at 70% and the text panes will grow/shrink as the frame is resized.

    0 讨论(0)
提交回复
热议问题