IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Composants Java Discussion :

[XML] & [JTable]


Sujet :

Composants Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre régulier
    Inscrit en
    Janvier 2008
    Messages
    7
    Détails du profil
    Informations forums :
    Inscription : Janvier 2008
    Messages : 7
    Par défaut [XML] & [JTable]
    Salut,

    Je suis étudiant en deuxième année info et j'ai un petit souci au niveau d'affichage de donnée à partir d'un fichier xml dans un JTable. Pour être plus précis, mon JTable affiche une table pour chaque élément demandé au lieu de les lister.

    voici mon fichier xml:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    <?xml version="1.0" encoding="UTF-8"?>
    <container>
      <job num="12345656">
        <customer>
          <name>John Smith</name>
          <shopName>Omega</shopName>
          <contactNumber>006139876566</contactNumber>
        </customer>
        <watch mark="Rolex">
          <workRequiries>Battery</workRequiries>
          <dateRecieve>2009-10-29</dateRecieve>
          <dateSend>2009-10-30</dateSend>
          <cost>2000</cost>
        </watch>
        <commentary>Battery HS</commentary>
      </job>
      <job num="1234567676">
        <customer>
          <name>John Connor</name>
          <shopName>Swatch Group</shopName>
          <contactNumber>006139787887</contactNumber>
        </customer>
        <watch mark="Swatch">
          <workRequiries>Cells</workRequiries>
          <dateRecieve>2009-09-12</dateRecieve>
          <dateSend>2009-10-31</dateSend>
          <cost>200</cost>
        </watch>
        <commentary>Buy complementary...</commentary>
      </job>
    </container>

    et voici mon code:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
     
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
     
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
     
    public class XmlJTable extends JPanel {
     
    private boolean DEBUG = false;
     
    	static org.jdom.Document document;
    	static Element racine;
     
    	public SimpleTableDemo() {
    		super(new GridLayout(1,0));
     
     
    		SAXBuilder sxb = new SAXBuilder();
    		try {
     
    			document = sxb.build(new File("test.xml"));
    		} catch (Exception e5) {
    		}
     
     
     
    		racine = document.getRootElement();
    		System.out.println("racine "+racine);
    		List listJob = racine.getChildren("job");
    		System.out.println(listJob.size());
     
    		Iterator i = listJob.iterator();
    		while (i.hasNext()) {
     
    			Element courant = (Element) i.next();
     
    			String[] columnNames = {"Number",
    					"Costumer name",
    					"Shop name",
    					"Costomer contact",
    					"Watch mark",
    					"Work require",
    					"Recieve date",
    					"Send date",
    					"Cost",
    			"Commentary"};
    			String[][] data = {
    					{
    						courant.getAttributeValue("num"), courant.getChild("customer").getChild("name").getText(),
    						courant.getChild("customer").getChild("shopName").getText()
    						, courant.getChild("customer").getChild("contactNumber").getText()
    						, courant.getChild("watch").getAttributeValue("mark"),courant.getChild("watch").getChild("workRequiries").getText()
    						,courant.getChild("watch").getChild("dateSend").getText(),courant.getChild("watch").getChild("dateSend").getText()
    						,courant.getChild("watch").getChild("cost").getText(),courant.getChild("commentary").getText()}
     
     
     
    			};
     
    			final JTable table = new JTable(data, columnNames);
    			table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    			table.setFillsViewportHeight(true);
     
    			if (DEBUG) {
    				table.addMouseListener(new MouseAdapter() {
    					public void mouseClicked(MouseEvent e) {
    						printDebugData(table);
    					}
    				});
    			}
     
    		   scrollPane = new JScrollPane(table);
     
     
    			add(scrollPane);
    		}
     
    	}
     
    	private void printDebugData(JTable table) {
    		int numRows = table.getRowCount();
    		int numCols = table.getColumnCount();
    		javax.swing.table.TableModel model = table.getModel();
     
    		System.out.println("Value of data: ");
    		for (int i=0; i < numRows; i++) {
    			System.out.print("    row " + i + ":");
    			for (int j=0; j < numCols; j++) {
    				System.out.print("  " + model.getValueAt(i, j));
    			}
    			System.out.println();
    		}
    		System.out.println("--------------------------");
    	}
     
    	/**
             * Create the GUI and show it.  For thread safety,
             * this method should be invoked from the
             * event-dispatching thread.
             */
    	private static void createAndShowGUI() {
    		//Create and set up the window.
    		JFrame frame = new JFrame("XmlJTable ");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		//Create and set up the content pane.
    		XmlJTable  newContentPane = new XmlJTable ();
    		newContentPane.setOpaque(true); //content panes must be opaque
    		frame.setContentPane(newContentPane);
     
    		//Display the window.
    		frame.pack();
    		frame.setVisible(true);
    	}
     
    	public static void main(String[] args) {
    		//Schedule a job for the event-dispatching thread:
    		//creating and showing this application's GUI.
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				createAndShowGUI();
    			}
    		});
    	}
    }
    et voici le résultat:

    Je vous remerci en avance!

  2. #2
    Membre expérimenté Avatar de uhrand
    Profil pro
    Développeur informatique
    Inscrit en
    Octobre 2009
    Messages
    203
    Détails du profil
    Informations personnelles :
    Localisation : Luxembourg

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Octobre 2009
    Messages : 203
    Par défaut
    Citation Envoyé par bond681 Voir le message
    affiche une table pour chaque élément demandé au lieu de les lister
    Essaie ceci:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    import javax.swing.*;
    import org.jdom.Document;
    import org.jdom.Element;
    import org.jdom.input.SAXBuilder;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
     
    import java.util.Vector;
    import javax.swing.table.DefaultTableModel;
     
    public class XmlJTable extends JPanel {
     
        private final boolean DEBUG = false;
        private Document document;
        private final Element racine;
        private final JScrollPane scrollPane;
        private final JTable table;
        private final Vector columnNames;
        private final Vector data;
     
        public XmlJTable() {
            super(new GridLayout(1, 0));
            columnNames = new Vector();
            columnNames.add("Number");
            columnNames.add("Costumer name");
            columnNames.add("Shop name");
            columnNames.add("Costomer contact");
            columnNames.add("Watch mark");
            columnNames.add("Work require");
            columnNames.add("Recieve date");
            columnNames.add("Send date");
            columnNames.add("Cost");
            columnNames.add("Commentary");
            data = new Vector();
            table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(900, 70));
            table.setFillsViewportHeight(true);
            if (DEBUG) {
                table.addMouseListener(new MouseAdapter() {
     
                    @Override
                    public void mouseClicked(final MouseEvent e) {
                        printDebugData(table);
                    }
                });
            }
            SAXBuilder sxb = new SAXBuilder();
            try {
                document = sxb.build(new File("test.xml"));
            } catch (Exception e5) {
                e5.printStackTrace();
            }
            racine = document.getRootElement();
            System.out.println("racine " + racine);
            List listJob = racine.getChildren("job");
            System.out.println(listJob.size());
            Iterator i = listJob.iterator();
            while (i.hasNext()) {
                Element courant = (Element) i.next();
                String[] rowData = {
                    courant.getAttributeValue("num"),
                    courant.getChild("customer").getChild("name").getText(),
                    courant.getChild("customer").getChild("shopName").getText(),
                    courant.getChild("customer").getChild("contactNumber").getText(),
                    courant.getChild("watch").getAttributeValue("mark"),
                    courant.getChild("watch").getChild("workRequiries").getText(),
                    courant.getChild("watch").getChild("dateSend").getText(),
                    courant.getChild("watch").getChild("dateSend").getText(),
                    courant.getChild("watch").getChild("cost").getText(),
                    courant.getChild("commentary").getText()
                };
                ((DefaultTableModel) table.getModel()).addRow(rowData);
            }
            scrollPane = new JScrollPane(table);
            add(scrollPane);
        }
     
        private void printDebugData(final JTable table) {
            int numRows = table.getRowCount();
            int numCols = table.getColumnCount();
            javax.swing.table.TableModel model = table.getModel();
            System.out.println("Value of data: ");
            for (int i = 0; i < numRows; i++) {
                System.out.print("    row " + i + ":");
                for (int j = 0; j < numCols; j++) {
                    System.out.print("  " + model.getValueAt(i, j));
                }
                System.out.println();
            }
            System.out.println("--------------------------");
        }
     
        /**
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
         */
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame("XmlJTable ");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            XmlJTable newContentPane = new XmlJTable();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
     
        public static void main(final String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
     
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }

  3. #3
    Membre régulier
    Inscrit en
    Janvier 2008
    Messages
    7
    Détails du profil
    Informations forums :
    Inscription : Janvier 2008
    Messages : 7
    Par défaut
    Merci de votre aide.

Discussions similaires

  1. Du XML au JTable
    Par leconteconte dans le forum Langage
    Réponses: 12
    Dernier message: 12/01/2012, 09h19
  2. Correspondance entre un JTable et un fichier xml
    Par bossy451 dans le forum Composants
    Réponses: 0
    Dernier message: 29/10/2008, 02h41
  3. Mapping XML et JTable ?
    Par budhax dans le forum Format d'échange (XML, JSON...)
    Réponses: 1
    Dernier message: 01/07/2007, 15h52

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo