1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class TestComboXML {
private JFrame fenetre;
private JComboBox combobox;
public List<String> lireFichierXML(InputStream fichierConfig) {
ArrayList<String> liste = new ArrayList<String>();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse(fichierConfig);
NodeList configs = document.getElementsByTagName("config");
for (int i = 0; i < configs.getLength(); i++) {
Element config = (Element) configs.item(i);
NodeList versions = config.getElementsByTagName("version");
for (int j = 0; j < versions.getLength(); j++) {
Element version = (Element) versions.item(j);
Element nom = (Element) version.getElementsByTagName("nom")
.item(0);
liste.add(nom.getTextContent());
}
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return liste;
}
public void initAndDisplay() {
List<String> liste = lireFichierXML(getClass().getResourceAsStream(
"TestComboXML.xml"));
fenetre = new JFrame();
combobox = new JComboBox(liste.toArray());
fenetre.getContentPane().add(combobox);
fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fenetre.pack();
fenetre.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TestComboXML application = new TestComboXML();
application.initAndDisplay();
}
});
}
} |
Partager