首页 文章

在向JScrollPane添加越来越多的JButton时,如何保持JButton的大小不变?

提问于
浏览
-1

我正在开发一个项目,应用程序需要能够在按钮上包含一些图像 . 每个按钮的长度和宽度应相同 . 应用程序中应该有大约10到20个按钮 . 所以我决定使用JScrollPane水平组织所有JButton . 首先,我将所有这些JButton添加到JPanel中,将其布局设置为GridLayout,其中包含1列和10行 . 然后将JPanel添加到JScrollPane中 . 结果,所有按钮都具有相同的大小 . 但问题是JScrollPane中的JScrollBar无法移动(可能因为它不足以超过JScrollPane的长度或GridLayout总是调整每个按钮的长度) . 所以我试着添加更多的JButton到20(图2) . 那么JScrollPane中的JScrollBar是启用的,我可以移动它 . 但不幸的是,每次添加更多按钮时,JScrollPane中的所有JButton都越来越短 .

我认为这是因为我设置为JPanel的GridLayout会自动调整每个组件的大小 . 所以我尝试使用FlowLayout,但它并不像预期的那样满意,因为JButton太小而无法调整大小(图3) . 我只是想在每次添加更多按钮或能够设置其大小时保持每个按钮的大小而不改变 .

那么有没有人有过这方面的经验,可以分享吗?

public class Testing
    {

        public Testing()
        {
            JFrame frm = new JFrame();
            JPanel panel = new JPanel();
            JScrollPane sc = new JScrollPane();

            // init frame
            frm.setSize(1366, 768);
            frm.setLayout(new GridLayout(5, 1, 10, 10));

            // init panel
            panel = new JPanel();
            panel.setLayout(new FlowLayout(FlowLayout.LEFT));

            // set some JScrollpane properties
            sc.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
            sc.setViewportView(panel);

            // add few button into panel
            for (int i = 0; i < 20; i++)
            {
                panel.add(new JButton("Button " + i));
            }

            frm.add(sc);
            frm.setVisible(true);
            frm.setLocationRelativeTo(null);
        }

        public static void main(String[] ar)
        {

            new Testing();
        }
    }

enter image description here

enter image description here

enter image description here

1 回答

  • 0

    好的..幸运的是,我偶然可以找到答案 . 要在JScrollPane中设置相同大小的所有组件,只需将JPanel的布局设置为FlowLayout,并使用setPreferredSize()而不是setSize()调整要添加到JPanel中的控件 . 它会像魅力一样工作 . :)

    链接:Giulio Biagini

相关问题