编辑jTable并将结果保存到XML

时间:2014-01-31 12:00:20

标签: java xml swing jtable

我有ReadXMLFile来获取数据,我将数据保存到ArrayList,接下来我从这个ArrayList打印表,Cell是可编辑的,我想编辑单元格或删除行,所以我该如何将结果保存到XML ?另外,我想通过示例在记事本外部修改xml文件时更新表。

  package net.kxyz;

  import java.awt.Dimension;
  import java.awt.GridLayout;
  import java.util.ArrayList;
  import javax.swing.JScrollPane;
  import javax.swing.JTable;
  import javax.swing.table.AbstractTableModel;

  /**
   *
        * @author kuman
   */
  public class Table extends javax.swing.JPanel {

 ReadXMLFile readXMLFile = new ReadXMLFile();
/**
 * Creates new form Table
 */
private boolean DEBUG = false;

 public Table() {

      super(new GridLayout(1, 0));
       System.out.println("SIEMANKO TABLE");
      readXMLFile.Read();
      ArrayList<Book> list = readXMLFile.getBook();

      list.add(new Book("3", "TYT", "AYUT", "231423"));
      list.get(0);
      JTable table = new JTable(new MyTableModel(list));
      table.setPreferredScrollableViewportSize(new Dimension(500, 70));
      table.setFillsViewportHeight(true);
       table.isCellEditable(0, 0);
      JScrollPane scrollPane = new JScrollPane(table);
      add(scrollPane);
 }

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
    );
}// </editor-fold>
// Variables declaration - do not modify
// End of variables declaration
  }


  class MyTableModel extends AbstractTableModel {
      private String[] columnNames = { "ID", "Title", "Author",
                "Year", "State" };
      ArrayList<Book> list = null;

      MyTableModel(ArrayList<Book> list) {
           this.list = list;
      }

      public int getColumnCount() {
           return columnNames.length;
      }

      public int getRowCount() {
           return list.size();
      }

      public String getColumnName(int col) {
           return columnNames[col];
      }

      public Object getValueAt(int row, int col) {

           Book object = list.get(row);

           switch (col) {
           case 0:
                return object.id;
           case 1:
                return object.title;
           case 2:
                return object.author;
           case 3:
                return object.year;
           case 4:
                return object.state;
           default:
                return "unknown";
           }
      }

@Override
      public Class getColumnClass(int c) {
           return getValueAt(0, c).getClass();
      }

       boolean[] canEdit = new boolean[]{
            false, false, true, false, true,
    };

@Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit[columnIndex];
    }

    public void setValueAt(Object value, int row, int col){



           switch (col) {
           case 0:
               // id not editable  list.get(row).setId((int)value);
           case 1:
                list.get(row).setTitle((String)value);
               break;
           case 2:
               list.get(row).setAuthor((String)value);
               break;
           case 3:
               list.get(row).setYear((String)value);
               break;
           case 4:
                list.get(row).setState(Boolean.valueOf((String)value));
               break;

           }
    fireTableCellUpdated(row, col);
}

 }

ReadXMLFile.class

   package net.kxyz;

   import java.io.File;
   import java.io.IOException;
   import java.util.ArrayList;
   import java.util.List;
   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.Node;
   import org.w3c.dom.NodeList;
   import org.xml.sax.SAXException;

   /**
    *
    * @author kuman
    */
   public class ReadXMLFile {

    File fXmlFile = new File("/baza.xml");

    public ArrayList<Book> getBook() {
    return book;
    }
    ArrayList<Book> book = new ArrayList<>() ;
public void Read() {
    try {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);


doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

NodeList nList = doc.getElementsByTagName("book");

for (int temp = 0; temp < nList.getLength(); temp++) {

    Node nNode = nList.item(temp);

    System.out.println("\nReading node :" + nNode.getNodeName());
            Book tempBook = new Book();
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {

        Element eElement = (Element) nNode;

                tempBook.setId(eElement.getAttribute("id"));
                tempBook.setTitle(eElement.getElementsByTagName("title").item(0).getTextContent());
                tempBook.setAuthor(eElement.getElementsByTagName("author").item(0).getTextContent());
                tempBook.setYear(eElement.getElementsByTagName("year").item(0).getTextContent());
                tempBook.setState(Boolean.valueOf(eElement.getElementsByTagName("state").item(0).getTextContent()));
                System.out.println("TEMP : " + temp);
                System.out.println("id : " + tempBook.getId());
                System.out.println("title : " + tempBook.getTitle());
                System.out.println("author : " + tempBook.getAuthor());
                System.out.println("year : " + tempBook.getYear());
                System.out.println("state : " + tempBook.isState());

                book.add(temp, tempBook);

    }
}

      } catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
       }
     }
   }

Book.class

   package net.kxyz;

   /**
    *
    * @author kuman
    */
   public class Book {
String id;
String title;
String author;
String year;
Boolean state;

public Book() {};
public Book(String id, String title, String author, String year) {
    this.id = id ;
    this.title = title;
    this.author = author;
    this.year = year;
    this.state = true;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}


public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public Boolean isState() {
    return state;
}

public void setState(Boolean state) {
    this.state = state;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getYear() {
    return year;
}

public void setYear(String year) {
    this.year = year;
}



   }

2 个答案:

答案 0 :(得分:0)

  

如何将结果保存到XML?

据我所知,你没有在TableModel中实现setValueAt()方法。保存更改的位置?

实际上在编辑之后你应该通过MyTableModel获取List?并将其存储为xml。

答案 1 :(得分:0)

您需要按如下方式实现JTableListener:

table.getModel()。addTableModelListener(new TableModelListener(){

  public void tableChanged(TableModelEvent e) {
     // your code goes here;
  }
});

当检测到对表的更改时,您需要将表的字段转换回XML。 此外,您可以实现WatchService来监视XML文件,当检测到文件的任何更改时,您可以通过调用ReadFromXML来重新加载表