昨天我从这个网站的用户那里得到了很大的帮助,我决定在这里问另一个问题,希望你们能帮助我。 我想编写一个包含组件的框架。它们需要位于 JPanel 上,并且 JPanel 应该位于 JScrollPane 中。
现在的问题是我需要为面板使用FlowLayout,因为我不知道我的面板中有多少个组件。
如果我在 JScrollPane 中使用 FlowLayout,它不会创建新行,而只是水平移动,这在实际应用程序中看起来非常奇怪。我真正想要的是,如果窗口结束,一条新的线就会接近。
问题是如何解决这个问题。我不能放置preferredSize,因为垂直ScrollBar不会比我放置preferredSize更远,所以我真的不知道该怎么做......也许改变布局?我将不胜感激任何帮助!
问题的示例代码:
public class scroller extends JFrame {
Container c;
JPanel p;
JScrollPane pane;
JButton button1;
JButton button2;
JButton button3;
JButton button4;
public scroller() {
c = getContentPane();
c.setLayout(new BorderLayout());
p = new JPanel();
p.setLayout(new FlowLayout());
pane = new JScrollPane(p);
button1 = new JButton("OK1");
p.add(button1);
button2 = new JButton("OK2");
p.add(button2);
button3 = new JButton("OK3");
p.add(button3);
button4 = new JButton("OK4");
p.add(button4);
p.setVisible(true);
c.add(pane,BorderLayout.CENTER);
}
public static void main(String[] args) {
scroller window = new scroller();
window.setSize(200,200);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
最佳答案
I cant put a preferredSize, because the vertical ScrollBar will not go further than I put the preferredSize
正确,当组件添加到面板时,需要动态计算preferredSize()。 FlowLayout 的默认首选大小计算假定单行组件。
所以解决方案是使用不同的布局管理器。
WrapLayout扩展 FlowLayout 并覆盖首选大小计算,以在组件换行到新行时提供首选宽度和高度。
关于Java JScrollPane 和 FlowLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48269796/