每次单击程序中的按钮时,我都会向 JPanel
添加 5 个新行。最终,行溢出,我想添加一个 JScrollPane,这样我就可以向下滚动并查看新行。
我知道如何让它在 TextArea
上工作,但我似乎不知道如何在我有 GridBagLayout
时让它工作。下面,我将附上用于设置面板的代码。
JPanel panelMain = new JPanel();
getContentPane().add(panelMain);
JPanel panelForm = new JPanel(new GridBagLayout());
panelMain.add(panelForm);
JScrollPane scrollpane = new JScrollPane(panelForm);
panelMain.add(scrollpane);
当我运行时,我的代码得到一个包含 GridBagLayout
的框,但滚动 Pane 无处可见。
最佳答案
JPanel panelMain = new JPanel();
getContentPane().add(panelMain);
您通常会将滚动 Pane 直接添加到框架中。不需要“panelMain”。
panelMain.add(panelForm);
不需要该行。一个组件只能属于一个父组件。稍后将“panelForm”添加到滚动 Pane 。
所以基本代码是:
JPanel panelForm = new JPanel(new GridBagLayout());
JScrollPane scrollpane = new JScrollPane(panelForm);
frame.add(scrollpane);
but the scrollpane is nowhere to be seen.
默认情况下,滚动条仅在需要时出现。添加空面板不会导致显示滚动条。单击按钮几次,然后使用适当的 GridBagConstraints 将子组件添加到“panelForm”中。然后您将需要使用:
panelForm.revalidate();
panelForm.repaint();
revalidate() 会调用布局管理器,以便滚动 Pane 可以确定是否需要滚动条。
关于java - 将 JScrollPane 添加到 GridBagLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49460779/