【问题标题】:How to keep JButtons' size remain the same when added more and more JButton to JScrollPane?当向 JScrollPane 添加越来越多的 JButton 时,如何保持 JButton 的大小保持不变?
【发布时间】:2017-01-14 14:20:22
【问题描述】:

我正在开发一个应用程序需要能够在按钮上包含一些图像的项目。每个按钮的长度和宽度应相同。应用程序中应该有大约 10 到 20 个按钮。于是我决定使用 JScrollPane 来水平组织所有的 JButton。首先,我将所有这些 JButton 添加到 JPanel 中,该 JPanel 将其布局设置为 1 列和 10 行的 GridLayout。然后将该 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();
        }
    }

【问题讨论】:

    标签: java swing jbutton jscrollpane


    【解决方案1】:

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

    链接:Giulio Biagini

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2019-12-26
      • 2019-05-15
      相关资源
      最近更新 更多