ScrollPane未在JLabel上显示

时间:2015-05-08 07:34:01

标签: java swing jscrollpane jlabel

当我运行此程序时,我在Label上看不到滚动条。我错过了什么?

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 个答案:

答案 0 :(得分:3)

要查看滚动条,请输入&#34;消息&#34; 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);
    }