【发布时间】: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