我有一个窗口,包含一个框架和 JScrollBar。 JScrollBar 有面板,如果添加了任何子组件,我想在运行时更改其大小。子组件大小是恒定的,不应改变。
我禁用了水平滚动条。因此,如果子组件的放置超过面板宽度,它应该转到下一行,并且面板高度应该自动更改。
这是代码片段
JScrollPane scrollPane = new JScrollPane();
menuPane = new JPanel();
menuPane.setLayout(new FlowLayout(FlowLayout.CENTER));
scrollPane.setViewportView(menuPane);
MenuTray mtFile = new MenuTray("File"); // MenuTray extends JPanel
menuPane.add(mtFile);
Menu mNew = new Menu((new ImageIcon(MenuScreen.class.getResource("/com/srinar/res/New.png"))), "New"); // Menu extends JLabel
mtFile.add(mNew);
frame.getContentPane().add(scrollPane);
最佳答案
. So if placement of Child Component exceeds panel width, it should go to next row and panel height should change automatically
FlowLayout 将自动换行组件,但不会重新计算新行上组件的首选大小。
您可以使用 Wrap Layout它扩展了 FlowLayout,以便在组件换行时可以正确地重新计算首选大小。
请注意,即使您不使用滚动 Pane ,也会发生换行。
关于java - 如果在运行时添加子组件,如何调整面板大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37315506/