3

我有一个带有流布局的包含面板 JPanel ,包含面板位于JScrollPane中,包含面板包含一堆其他JPanel内部面板。所有内板都具有相同的尺寸。如果有更多面板,则包含面板可以保持其宽度,然后将它们向下网格化,如果有更多面板,则包含面板可以保持其高度,则内部面板在同一网格中对齐,但除外以最后一行为中心的最后一行。

虽然我调整对话框的大小,包含面板扩展并且布局流布局执行其职责,但是尽管面板的大小超过了JScrollPane的边界,但滚动条不会出现。

动态调整包含面板的大小时,如何控制滚动条的外观?

至于图像,他们应该总结一下:

替代文字

扩展对话框宽度后:

替代文字

亚当

4

1 回答 1

4

您需要使包含面板实现Scrollable,并根据宽度设置首选的可滚动视口大小。

import java.awt.*;
import javax.swing.*;

public class Test
{
    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                JPanel container = new ScrollablePanel();
                container.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
                for( int i = 0; i < 20; ++i )
                {
                    JPanel p = new JPanel();
                    p.setBorder(BorderFactory.createLineBorder(Color.RED));
                    p.setPreferredSize(new Dimension(50, 50));
                    p.add(new JLabel("" + i));
                    container.add(p);
                }

                JScrollPane scroll = new JScrollPane(container);
                scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

                JFrame f = new JFrame("Test");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                    
                f.getContentPane().add(scroll);                    
                f.pack();
                f.setSize(250, 300);
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}

class ScrollablePanel extends JPanel implements Scrollable
{
    public Dimension getPreferredSize()
    {
        return getPreferredScrollableViewportSize();
    }

    public Dimension getPreferredScrollableViewportSize()
    {
        if( getParent() == null )
            return getSize();
        Dimension d = getParent().getSize();
        int c = (int)Math.floor((d.width - getInsets().left - getInsets().right) / 50.0);
        if( c == 0 )
            return d;
        int r = 20 / c;
        if( r * c < 20 )
            ++r;
        return new Dimension(c * 50, r * 50);
    }

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

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

    public boolean getScrollableTracksViewportHeight()
    {
        return false;
    }

    public boolean getScrollableTracksViewportWidth()
    {
        return getParent() != null ? getParent().getSize().width > getPreferredSize().width : true;
    }
}

为简单起见,所有数字都经过硬编码,但您应该明白这一点。

于 2010-10-07T04:26:34.480 回答