这是我正在尝试做的事情:
我已经解决了这个问题,因为XML文件本身的主体中有几个具有相同标签的元素,因此,该元素在下拉列表中出现不止一次,是在我的for循环中有一种方法来比较已经存在的东西并删除重复项吗?
这是我得到的整个方法
public static void readXML(String filePath) {
try {
//Gets selected XML file
File XmlFile = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(XmlFile);
//Searches all text
doc.getDocumentElement().normalize();
//Make a non-editable combo box
JComboBox<String> comboBox = new JComboBox<String>();
comboBox.setEditable(false);
//Get all the XML elements from the file
NodeList list = doc.getElementsByTagName("*");
//TODO:
//Make sure all XML elements only appear once in the list
//Populate combobox with all elements from input file
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String item = element.getNodeName().toString();
//Add comparison here??
comboBox.addItem(item);
}
//Add Combo box and refresh the frame window so that it appears
buttonPanel.add(comboBox);
frame.revalidate();
//Add action listener show which XML element has been selected
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//Get the source of the component, which is the combo box
JComboBox<?> comboBox = (JComboBox<?>) event.getSource();
//Print the selected item
String selected = comboBox.getSelectedItem().toString();
log.append("The selected XML element is: " + selected + newline);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
编辑:
我面临的第二个问题是确保所有元素都按字母顺序排列。我通过执行以下操作解决了这个问题:
// Make a sublist so that the elements can be sorted
List<String> subList = allValues.subList(0, allValues.size());
Collections.sort(subList);
// Add the items from the subList to the comboBox
for (int j = 0; j < subList.size(); j++) {
String listItem = subList.get(j).toString();
comboBox.addItem(listItem);
}
答案 0 :(得分:1)
声明一个ArrayList,
如果您使用的是Java 7,
ArrayList<String> allValues = new ArrayList<>();
或者如果您使用的是早期版本的Java,
ArrayList<String> allValues = new ArrayList<String>();
在for
循环中,
for (int i = 0; i < list.getLength(); i++) {
Element element = (Element)list.item(i);
String item = element.getNodeName().toString();
if (!allValues.contains(item)){
comboBox.addItem(item);
allValues.add(item);
}
}