JScrollPanel中View不斷變寬的問題(如何限制View寬度)

當JScrollPane中的View包含一個JLabel,如果這個JLabel很長,那麼在一開始,水平滾動條是隱藏的。這時候,如果我們慢慢拖動窗口使JScrollPane變寬,那麼View也變寬了(因爲JLabel很長)。但是如果這時候拖動窗口使JScrollPane變窄,View的寬度沒有變窄!水平滾動條出現了!


我們期望的結果是,JScrollPane變窄的時候,JLabel也變窄。


但是我們發現JTextArea在JScrollPane中的時候,JScrollPane變窄,JTextArea也會變窄。這是爲啥呢?


其實是因爲JTextArea實現了Scrollable接口,JScrollPane會因爲View是否實現Scrollable接口而有不同的表現。


參考JTextArea中Scrollable的實現(JTextComponent的實現),相應的,我們可以讓View按照如下的方法實現Scrollable。此處爲MyFixedWidthPanel。

public class MyFixWidthPanel extends JPanel implements Scrollable {
    public MyFixWidthPanel() {
        super();
    }

    public MyFixWidthPanel(LayoutManager layout) {
        super(layout);
    }

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

    @Override
    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
        switch (orientation) {
            case SwingConstants.VERTICAL:
                return visibleRect.height / 10;
            case SwingConstants.HORIZONTAL:
                return visibleRect.width / 10;
            default:
                throw new IllegalArgumentException("Invalid orientation: " + orientation);
        }
    }

    @Override
    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
        switch (orientation) {
            case SwingConstants.VERTICAL:
                return visibleRect.height;
            case SwingConstants.HORIZONTAL:
                return visibleRect.width;
            default:
                throw new IllegalArgumentException("Invalid orientation: " + orientation);
        }
    }

    @Override
    public boolean getScrollableTracksViewportWidth() {
        return true;
    }

    @Override
    public boolean getScrollableTracksViewportHeight() {
        return false;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章