Search code examples
javaswingjscrollpanejdialog

Positioning and Sizing JScrollBar on a JDialog


I am having trouble getting my scroll bar to work with my JDialog. I am obviously not adding the scroll bar properly but I am unable to figure out what I am doing wrong.

Clarification update

timeLineDialog = new JDialog();
scroller=new JScrollPane();
scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
timeLineDialog.setLayout(layout);
timeLineDialog.setModalityType(ModalityType.MODELESS);
timeLineDialog.setTitle("Time Line Settings");
timeLineDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
timeLineDialog.setPreferredSize(new Dimension(1004,400));

// all my components are added to the JDialog here
// I use GridBagLayout to essentially create rows of components

timeLineDialog.add(...);

timeLineDialog.add(scroller);
timeLineDialog.pack();
timeLineDialog.setLocationRelativeTo(GUI.getInstance().getFrame());
timeLineDialog.setVisible(true);

While I get the scroll bar it is small and is placed only at the end of the 3rd row.

enter image description here

It never really scrolls anything and as I add rows the layout manager simply makes things smaller to get it to fit and the buttons at the bottom begin to move off the pane. What am I doing wrong? TIA.


Solution

  • // all my components are added to the JDialog here // I use GridBagLayout to essentially create rows of components

    You never add any component to the JScrollPane.

    The code should be:

    JPanel panel = new JPanel( new GridBagLayout() );
    panel.add(...);
    panel.add(...);
    
    //scroller=new JScrollPane();
    scroller=new JScrollPane(panel);
    ...
    //timeLineDialog.getContentPane().add(scroller);
    timeLineDialog().add(scroller);
    

    Note, there is no need for the getContentPane() method, the component will automatically be added to the content pane.