JFrame 中的 JScrollPane

JScrollPane in JFrame

我想写一个简单的Java程序,它由一个JFrame集成了一个JScrollPane.只是没有按照我的方式工作。

我的方法有什么问题?

public class TestView {

    JFrame frame;
    JScrollPane scrollPane;

    public TestView(){

        frame = new JFrame();
        scrollPane = new JScrollPane();    
        scrollPane.add(new JLabel("Klick me"));
        scrollPane.setMinimumSize(new Dimension(200,200));

        frame = new JFrame();
        frame.getContentPane().add(scrollPane);
        frame.setSize(200,200);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void createAndShowGui(){
        TestView tv = new TestView();
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 createAndShowGui();
            }
        });

使用例如:

final JPanel myPanel = new JPanel();
myPanel.setPreferredSize(new Dimension(50, 50));  
final JScrollPane scrollPane = new JScrollPane(myPanel);

setMinimumSize 将被忽略。

如果问题是您没有在滚动窗格中看到您的标签,您可能需要使用

scrollpane.setViewportView(new JLabel("Klick me"));

而不是

scrollPane.add(new JLabel("Klick me"));

此外,我建议您创建一个 JPanel,给它一个布局,然后将您的标签放在那里,而不是将标签传递给滚动窗格。然后将此面板设置为视口。

请看

Difference between JscrollPane.setviewportview vs JscrollPane.add