有沒有辦法將數組中的所有字符串添加到JList中?我使用的是DefaultListModel,我不知道如何使用它。沒有辦法只是使用addElement然後添加數組?我試過了,但它不起作用。Java:DefaultListModel和數組
這裏是我的代碼:
package program;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
public class Main{
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel pane = new JPanel();
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
//JFrame, frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//JPanel, panel
pane.setLayout(new FlowLayout());
frame.add(pane);
//JList, list
String[] lists = {"asjd.txt", "okay.ss", "jsjs.okay.txt"};
model.addElement(lists);
JScrollPane listScroller = new JScrollPane(list);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setLayoutOrientation(JList.VERTICAL);
list.setVisibleRowCount(3);
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setBounds(5, 5, 200, 300);
pane.add(listScroller);
}
}
好的,謝謝:) – Lezorical