Adding a JScrollPane to JDialog

2020-05-09 04:01发布

问题:

I have a working JDialog and now I want to add scroll bars to it. The documentation is a bit confusing to me. Do I add the dialog to the JScrollPane or vice-versa?

It seems like all the examples have a JPanel in the dialog and the panel is scrollable. I have a dialog that grows dynamically so I want the dialog itself to be scrollable. Can someone point me in the right direction?

Reply to Andrew Thompson

Thanks for the reply.

I let the size be determined by the layout manager at this point. I'm not exactly sure yet how big to let it get yet so I have not set any sizes. It just grows as I add rows. That will be part of this development phase. The width will not change, just the height. I display the dialog using 'invokelater'. This is the relevant code:

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);

I want the scroll bars on the right side of the dialog pane.

回答1:

I think you have to create a JDialog, then add a JScrollPane to it and your content inside that. The following code worked for me:

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("<html><body><p>Content<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>Content<br><br><br><br><br><br>Content</p></body></html>");

    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);

    }
}

Hope this helps.