[英]Java: DefaultListModel and arrays
Is there a way to add all the Strings in an array to a JList? 有没有办法将数组中的所有字符串添加到JList? I am using the DefaultListModel and I have no idea how to use it.
我正在使用DefaultListModel,我不知道如何使用它。 Isn't there a way to just use addElement then add the array?
有没有办法只使用addElement然后添加数组? I tried but it does not work.
我试过但它不起作用。
Here is my code: 这是我的代码:
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);
}
}
Create your own loop: 创建自己的循环:
for (String item: lists)
model.addElement( item );
Also, the frame should be made visible AFTER all the components have been added to the frame. 此外,在将所有组件添加到框架后,框架应该可见。
listScroller.setPreferredSize(new Dimension(250, 80));
listScroller.setBounds(5, 5, 200, 300);
Don't use setPreferredSize(). 不要使用setPreferredSize()。 You already used setVisibleRowCount() to control the size of the JList.
您已经使用setVisibleRowCount()来控制JList的大小。
Don't use setBounds(). 不要使用setBounds()。 That is the job of the layout manager.
这是布局管理器的工作。
JList contains a constructor JList包含一个构造函数
JList(ListModel <E> dataModel)
which means you could create your own ListModel object which accepts your array. 这意味着您可以创建自己的ListModel对象来接受您的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.