Olá, eu fiz uma pequena tabelinha, eu gostaria que os dados dessa tabelinha fossem sincronizados com um arquivo xml, pesquisei bastante, até que encontrei a solução, bom até a pouco tempo funcionava, bastou eu mudar os valores dos atributos, então eu fiz a seguinte classe:
package Interface;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.MaskFormatter;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import Interface.Tema;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.io.OutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.ArrayList;
public class TabelaTemas extends JPanel {
private static final long serialVersionUID = 1L;
public static JButton adicionar = new JButton("Adicionar");
public static JButton remover = new JButton("Remover");
MyTableModel model = new MyTableModel();
public static JTable table;
public static ArrayList<Tema> linhas = new ArrayList<>();
final String USERDIR = System.getProperty("user.home");
public TabelaTemas() {
super(new BorderLayout());
table = new JTable(model) {
private static final long serialVersionUID = 1L;
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
return c;
}
public Component prepareEditor(TableCellEditor editor, int row, int column) {
Component c = super.prepareEditor(editor, row, column);
c.setFont(new Font("Comic Sans MS", Font.BOLD, 13));
return c;
}
};
model.addTableModelListener(new TableModelListener(){
public void tableChanged(TableModelEvent evento) {
switch(evento.getType()){
case TableModelEvent.UPDATE:
try{
final int linha1 = evento.getFirstRow();
System.out.println("começou a editar");
final Tema tema = linhas.get(linha1);
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File(USERDIR+"/TFKProgramFiles/EU/temas.xml"));
Element root = new Element("temas");
Element Etema = new Element("tema");
Attribute progresso = new Attribute("progresso",tema.getFeito() != null ? tema.getFeito() : "");
Attribute nome = new Attribute("nome",tema.getNome() != null ? tema.getNome() : "");
Attribute materia = new Attribute("materia",tema.getMateria() != null ? tema.getMateria() : "");
Attribute dia = new Attribute("dia",tema.getDiaDaSemana() != null ? tema.getDiaDaSemana() : "");
Etema.setAttribute(progresso);
Etema.setAttribute(nome);
Etema.setAttribute(materia);
Etema.setAttribute(dia);
root.addContent(Etema);
doc.setRootElement(root);
XMLOutputter xout = new XMLOutputter();
xout.output(doc, new FileWriter(USERDIR+"/TFKProgramFiles/EU/temas.xml"));
System.out.println("terminou de editar");
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
});
table.setRowHeight(20);
table.getTableHeader().setReorderingAllowed(false);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JScrollPane scrollPane = new JScrollPane(table);
String[] dados = { "Segunda", "Terça", "Quarta", "Quinta", "Sexta","Sabado" };
table.getColumnModel().getColumn(3).setCellEditor(new MyComboBoxEditor(dados));
String[] dados2 = { "Começar", "Pronto", "Entregar" };
table.getColumnModel().getColumn(0).setCellEditor(new MyComboBoxEditor(dados2));
JLabel titulo = new JLabel("Registre seus temas:");
JPanel controles = new JPanel(new FlowLayout());
controles.add(adicionar);
controles.add(remover);
add(titulo, BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
add(controles, BorderLayout.SOUTH);
}
}
class MyComboBoxRenderer extends JComboBox<Object> implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyComboBoxRenderer(String[] items) {
super(items);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
super.setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(table.getBackground());
}
setSelectedItem(value);
return this;
}
}
class MyComboBoxEditor extends DefaultCellEditor {
private static final long serialVersionUID = 1L;
public MyComboBoxEditor(String[] items) {
super(extracted(items));
}
private static JComboBox<?> extracted(String[] items) {
return new JComboBox<Object>(items);
}
}
class MyJFTEditor extends DefaultCellEditor {
private static final long serialVersionUID = 1L;
public MyJFTEditor(MaskFormatter cep) {
super(new JFormattedTextField(cep));
}
}
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = { "Progresso", "Nome", "Materia", "Dia"};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return TabelaTemas.linhas.size();
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int linha, int coluna) {
switch (coluna) {
case 0:
return TabelaTemas.linhas.get(linha).getFeito();
case 1:
return TabelaTemas.linhas.get(linha).getNome();
case 2:
return TabelaTemas.linhas.get(linha).getMateria();
case 3:
return TabelaTemas.linhas.get(linha).getDiaDaSemana();
}
return null;
}
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return String.class;
}
return null;
}
public boolean isCellEditable(int row, int col) {
return true;
}
public void setValueAt(Object value, int row, int col) {
switch (col) {
case 0:
TabelaTemas.linhas.get(row).setFeito((String) value);
case 1:
TabelaTemas.linhas.get(row).setNome((String) value);
break;
case 2:
TabelaTemas.linhas.get(row).setMateria((String) value);
break;
case 3:
TabelaTemas.linhas.get(row).setDiaDaSemana((String) value);
break;
}
fireTableCellUpdated(row, col);
}
public void adicionar(Tema value) {
TabelaTemas.linhas.add(value);
fireTableDataChanged();
}
public void remover(int row) {
TabelaTemas.linhas.remove(row);
fireTableDataChanged();
}
public void removertudo() {
int quant = TabelaTemas.linhas.size();
for (int i = quant; i > 0; --i) {
TabelaTemas.linhas.remove(i - 1);
fireTableDataChanged();
}
}
}
class LimitedPlainDocument extends javax.swing.text.PlainDocument {
private static final long serialVersionUID = 1L;
private int maxLen = -1;
public LimitedPlainDocument() {
}
public LimitedPlainDocument(int maxLen) {
this.maxLen = maxLen;
}
public void insertString(int param, String str, javax.swing.text.AttributeSet attributeSet)
throws javax.swing.text.BadLocationException {
if (str != null && maxLen > 0 && this.getLength() + str.length() > maxLen) {
java.awt.Toolkit.getDefaultToolkit().beep();
return;
}
super.insertString(param, str, attributeSet);
}
}`
Porém quando tudo é escrito em disco, é retornada a seguinte exceção:
`
java.io.UTFDataFormatException: Invalid byte 2 of 3-byte UTF-8 sequence.
at org.apache.xerces.impl.io.UTF8Reader.invalidByte(Unknown Source)
at org.apache.xerces.impl.io.UTF8Reader.read(Unknown Source)
at org.apache.xerces.impl.XMLEntityScanner.load(Unknown Source)
at org.apache.xerces.impl.XMLEntityScanner.scanLiteral(Unknown Source)
at org.apache.xerces.impl.XMLScanner.scanAttributeValue(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanAttribute(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.DTDConfiguration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:217)
at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:277)
at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:264)
at org.jdom2.input.SAXBuilder.build(SAXBuilder.java:1116)
at Interface.TabelaTemas$2.tableChanged(TabelaTemas.java:76)
at javax.swing.table.AbstractTableModel.fireTableChanged(Unknown Source)
at javax.swing.table.AbstractTableModel.fireTableCellUpdated(Unknown Source)
at Interface.MyTableModel.setValueAt(TabelaTemas.java:244)
at javax.swing.JTable.setValueAt(Unknown Source)
at javax.swing.JTable.editingStopped(Unknown Source)
at javax.swing.AbstractCellEditor.fireEditingStopped(Unknown Source)
at javax.swing.DefaultCellEditor$EditorDelegate.stopCellEditing(Unknown Source)
at javax.swing.DefaultCellEditor.stopCellEditing(Unknown Source)
at javax.swing.JTable$GenericEditor.stopCellEditing(Unknown Source)
at javax.swing.DefaultCellEditor$EditorDelegate.actionPerformed(Unknown Source)
at javax.swing.JTextField.fireActionPerformed(Unknown Source)
at javax.swing.JTextField.postActionEvent(Unknown Source)
at javax.swing.JTextField$NotifyAction.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)`
E o arquivo fica assim:
<?xml version="1.0" encoding="UTF-8"?>
<temas>
<tema progresso="Começar" nome="" materia="" dia="Segunda" />
</temas>
Alguém sabe porque isso acontece?