使用布局管理器(如BorderLayout)将JScrollPane添加到JFrame中的指定位置,并设置好大小。
示例代码:
import java.awt.;
import javax.swing.;
public class ScrollPaneExample extends JFrame {
public ScrollPaneExample() {
setTitle("ScrollPane Example");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JList<String> list = new JList<>(new String[]{"Apple", "Banana", "Cherry", "Date", "Eggplant", "Fig", "Grape"});
JScrollPane scrollPane = new JScrollPane(list);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new ScrollPaneExample().setVisible(true));
}
}