java - ScrollPane not showing on JLabel

When I run this program, I don't see a scrollbar on the Label. What am I missing?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Util1
{
    public static void main(String[] args)
    {
        new Util1();
    }

    public Util1()
    {
        EventQueue.invokeLater(new Runnable() 
        {
            public void run() 
            {

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ExamplePane());

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true); 
            }
        });
    }

    protected class ExamplePane extends JPanel 
    {
        public ExamplePane() 
        {
            final JPanel panel = new JPanel(new GridBagLayout());
            final JLabel message = new JLabel("<html>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello</html>");

            message.setPreferredSize(new Dimension(500, 50));
            JScrollPane scroller = new JScrollPane( message, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scroller.setViewportView(message);

            panel.add(scroller);
            add(panel);
        }            
    }        
}

1 Answer

  1. Justin- Reply

    2019-11-13

    To see a scrollbar wrap the "message" JLabel into JPanel and then add this JPanel to JScrollPane like bellow:

        public ExamplePane() {
            final JPanel panel = new JPanel(new GridBagLayout());
            final JLabel message = new JLabel("<html>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello<br>Hello</html>");
            message.setPreferredSize(new Dimension(500, 50));
    
            final JPanel messagePanel = new JPanel();
            messagePanel.add(message);
    
            JScrollPane scroller = new JScrollPane(messagePanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scroller.setPreferredSize(new Dimension(100, 50));
    
            panel.add(scroller);
            add(panel);
        }
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>