Search code examples
javaswingjframejscrollpanenull-layout-manager

Issue creating Scrollable Pane with Swing


I have the following class...

public class MessageFrame extends JFrame {

public MessageFrame(List<HistoryMessage> messages){
    setLayout(null);
    JPanel container = new JPanel();
    JScrollPane scrPane = new JScrollPane(container);
    getContentPane().add(scrPane);
    int i = 1;
    for(HistoryMessage m : messages){
        //TODO: needs to be StringBuilder
        StringBuilder sb = new StringBuilder();
        sb.append("<html> <strong>");
        sb.append(m.getSender());
        sb.append(" ");
        Date d = new Date(m.getDate());
        sb.append(d);
        sb.append(":</strong>");
        sb.append(m.getPayload());
        sb.append("</html>");
        JLabel l = new JLabel(sb.toString());
        l.setBounds(30, i, 400, 50);
        i += 125;
        container.add(l);
    }
    setTitle("Messages");
    setSize(500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
}

}

This shows me nothing, however, if I don't use the scroll pane this works...

public MessageFrame(List<HistoryMessage> messages){
    setLayout(null);
    int i = 1;
    for(HistoryMessage m : messages){
        //TODO: needs to be StringBuilder
        StringBuilder sb = new StringBuilder();
        sb.append("<html> <strong>");
        sb.append(m.getSender());
        sb.append(" ");
        Date d = new Date(m.getDate());
        sb.append(d);
        sb.append(":</strong>");
        sb.append(m.getPayload());
        sb.append("</html>");
        JLabel l = new JLabel(sb.toString());
        l.setBounds(30, i, 400, 50);
        i += 125;
        add(l);
    }
    setTitle("Messages");
    setSize(500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    setVisible(true);
}

But no scrolling so only the first few show up, can someone help me with what I am missing?


Solution

  • setLayout(null);
    

    Don't use a null layout.

    l.setBounds(30, i, 400, 50);
    

    Don't use setBounds(...).

    Scrollbars will appear automatically when the preferred size of the component added to the scrollpane is greater than the size of the scroll pane.

    Let the layout managers to their jobs. Read the section from the Swing tutorial on Layout Managers and use an appropriate layout manager or combination of nested layout managers.