JLabel 上未显示 ScrollPane

ScrollPane not showing on JLabel

当我 运行 这个程序时,我没有在标签上看到滚动条。我错过了什么?

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

要查看滚动条,请将 "message" JLabel 包装到 JPanel 中,然后将此 JPanel 添加到 JScrollPane,如下所示:

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