如何在面板中添加 ScrollPane

How to add a ScrollPane in a Panel

我正在尝试在 JPanel 中放置一个滚动条。

我把我的代码放在 public static void main 上。

public static void main(String[] args) {
    JFrame frame = new JFrame("Outil Replacement");
    frame.setSize(930, 610);
    frame.setPreferredSize(new Dimension(930,400));

    JScrollPane scrollPane = new JScrollPane();

    scrollPane.setWheelScrollingEnabled(true);

    frame.add(scrollPane);
    frame.setContentPane(new Replacement().panelMain);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

它什么都不做。

只是一个表单视图。

有人有解决办法吗?

您宁愿将目标 JPanel 设置为 JScrollPane 视口视图 ,然后添加 JScrollPane,如下所示:

JScrollPane scrollPane = new JScrollPane(new Replacement().panelMain);

scrollPane.setWheelScrollingEnabled(true);

frame.setContentPane(scrollPane);

参见:JScrollPane(java.awt.Component)

并且:How to Use Scroll Panes