将JScrollPane添加到JDialog

我有一个工作的JDialog ,现在我想添加滚动条。 文档对我来说有点混乱。 我是否将对话框添加到JScrollPane ,反之亦然?

似乎所有示例都在对话框中有一个JPanel ,面板是可滚动的。 我有一个动态增长的对话框,所以我希望对话框本身可以滚动。 有人能指出我正确的方向吗?

回复安德鲁汤普森

谢谢回复。

我让尺寸由布局管理器决定。 我还不确定它到底有多大,所以我没有设置任何尺寸。 它随着我添加行而增长。 这将是这一发展阶段的一部分。 宽度不会改变,只是高度。 我使用’invokelater’显示对话框。 这是相关代码:

 timeLineDialog = new JDialog(); timeLineDialog.setLayout(layout); timeLineDialog.setModalityType(ModalityType.MODELESS); timeLineDialog.setTitle("Time Line Settings"); timeLineDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); . . . timeLineDialog.pack(); timeLineDialog.setLocationRelativeTo(GUI.getInstance().getFrame()); timeLineDialog.setVisible(true); 

在此处输入图像描述

我想要对话框窗格右侧的滚动条。

我认为你必须创建一个JDialog,然后在其中添加一个JScrollPane和你的内容。 以下代码对我有用:

 import javax.swing.JDialog; import javax.swing.JScrollPane; import java.awt.BorderLayout; import javax.swing.JLabel; public class Dialog extends JDialog { private final JScrollPane scrollPane = new JScrollPane(); //I added the breaks to the label below to be able to scroll down. private final JLabel lblContent = new JLabel("

Content















Content





Content

"); public static void main(String[] args) { Dialog dialog = new Dialog(); dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); dialog.setVisible(true); } public Dialog() { setBounds(100, 100, 450, 300); getContentPane().setLayout(new BorderLayout(0, 0)); getContentPane().add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(lblContent); } }

看起来如何

希望这可以帮助。