[英]Adding file to jlist
Adding file to jlist, I add to jframe, one jbutton, one jtextview and one jlist, I add file .txt but effectlly to jtextview ex: C:/Windows/file.txt 添加文件到jlist,我添加到jframe,一个jbutton,一个jtextview和一个jlist,我添加文件.txt,但实际上添加到jtextview,例如:C:/Windows/file.txt
JList.add(JList, null);
But theres something went wrong 但是出了点问题
Thank 谢谢
You need to work with the List Model for your JList. 您需要使用JList的列表模型。 You can't just directly add to a JList like you've done since the JList is so versatile to handle all sorts of Objects. 您不能像已经完成的那样直接将其添加到JList中,因为JList具有处理各种对象的通用性。 It's a little more complicated than that. 比这复杂一点。
First you want to make sure your JList actually contains a Default List Model: 首先,您要确保您的JList实际上包含一个默认列表模型:
// Make sure the JList contains a List Model
try {
DefaultListModel dlm = (DefaultListModel)yourJListName.getModel();
}
catch (Exception e) {
// Nope...so let's set one.
yourJListName.setModel(new DefaultListModel());
}
Now that your sure your JList contains a List Model you can add items to it. 现在,确保JList包含列表模型,您可以向其中添加项目。
// Get the current List Model for your JList
DefaultListModel dlm = (DefaultListModel)yourJListName.getModel();
// Declare a list to represent it.
JList list = new JList(dlm);
// Get the last position within the List so
// as to append to it.
int pos = list.getModel().getSize();
// Add the text from the JTextField into your JList.
dlm.add(pos, yourJTextFieldName.getText());
Perhaps create a Method to do the adding for you: 也许创建一个方法为您做添加:
public void addToJList(JList yourJList, String stringToAdd) {
// Make sure the JList contains a List Model
try {
DefaultListModel dlm = (DefaultListModel)yourJList.getModel();
}
catch (Exception e) {
// Nope...so let's set one.
yourJList.setModel(new DefaultListModel());
}
// Get the current List Model for your JList
DefaultListModel dlm = (DefaultListModel)yourJList.getModel();
// Declare a list to represent it.
JList list = new JList(dlm);
// Get the last position within the List so
// as to append to it.
int pos = list.getModel().getSize();
// Add the text from the JTextField into your JList.
dlm.add(pos, stringToAdd);
}
And how you might use it: 以及如何使用它:
addToJList(yourJListName, yourJTextFieldName.getText());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.