如何在 Java 中为 JList 添加 ScrollBar?
我们首先设置一个 JList 并添加项 -
List<String> myList = new ArrayList<>(10); for (int index = 0; index < 20; index++) { myList.add("List Item " + index); }
现在,我们将上述列表设置到一个新列表 -
final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()]));
现在,将 ScrollBar 设置到 JList -
JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(list); list.setLayoutOrientation(JList.VERTICAL);
以下是向 JList 添加 ScrollBar 的示例 -
示例
package my; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.List; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); List<String> myList = new ArrayList<>(10); for (int index = 0; index < 20; index++) { myList.add("List Item " + index); } final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()])); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(list); list.setLayoutOrientation(JList.VERTICAL); panel.add(scrollPane); JFrame frame = new JFrame("Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(500, 250); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
这将生成以下输出 -
广告