08.06.2013, 10:10. Показов 1577. Ответов 1
Нужно заполнить таблицу данными из xml, вывод сделал, с вводом что-то не выходит, не нашёл понятный пример.
Так вывожу данные:
Кликните здесь для просмотра всего текста
| Java |
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
| package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;
import javax.swing.JFileChooser;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import model.TableModel;
import view.MainFrame;
class SaveEvent implements ActionListener {
static final long serialVersionUID = 1L;
private MainFrame frame;
private TableModel model;
private File file;
public SaveEvent(MainFrame frame){
this.frame = frame;
}
public void actionPerformed(ActionEvent event)
{
this.model = this.frame.getTablePanel().getTableModel();
try{
DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = f.newDocumentBuilder();
JFileChooser fileChooser = new JFileChooser();
ProjectFileFilter xmlFilter = new ProjectFileFilter(".xml");
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(xmlFilter);
int result = fileChooser.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
String fileName = fileChooser.getSelectedFile().getAbsolutePath();
if (fileChooser.getFileFilter() == xmlFilter)
file = new File(fileName + ".xml");
else
file = new File(fileName);
if (!file.exists())
file.createNewFile();
Document doc = builder.newDocument();
Element tableEl = doc.createElement("students");
doc.appendChild(tableEl);
List<String> columns = this.frame.getTablePanel().getTableModel().getColumns();
for (int rowInd = 0; rowInd < model.getRowCount(); rowInd++){
Element rowEl = doc.createElement("student");
tableEl.appendChild(rowEl);
for (int columnInd = 0; columnInd < columns.size(); columnInd++){;
String header = columns.get(columnInd);
String value = model.getValueAt(rowInd, columnInd).toString();
Element cellEl = doc.createElement("cell");
Attr colAttr = doc.createAttribute("colName");
cellEl.setAttributeNode(colAttr);
rowEl.appendChild(cellEl);
colAttr.appendChild(doc.createTextNode(header));
cellEl.appendChild(doc.createTextNode(value));
}
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult resultStream = new StreamResult(file);
transformer.transform(source, resultStream);
}
}
catch(Exception exception){
exception.printStackTrace();
}
}
} |
|
Открытие файла и занесение данных в таблицу:
Кликните здесь для просмотра всего текста
| Java |
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
| package controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import model.Student;
import view.MainFrame;
class OpenEvent implements ActionListener {
String fileName;
MainFrame frame;
public OpenEvent(MainFrame frame){
this.frame = frame;
}
public void actionPerformed(ActionEvent event)
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser;
JFileChooser file = new JFileChooser();
ProjectFileFilter xmlFilter = new ProjectFileFilter(".xml");
file.addChoosableFileFilter(xmlFilter);
file.setCurrentDirectory(new File("."));
file.setAcceptAllFileFilterUsed(false);
int result = file.showOpenDialog(null);
if(result == JFileChooser.APPROVE_OPTION)
{
try
{
parser = factory.newSAXParser();
XMLRead saxp = new XMLRead();
fileName = file.getSelectedFile().getAbsolutePath();
File inputFile = new File(fileName);
parser.parse(inputFile, saxp);
List<Student> students = saxp.getStudents();
for(Student student: students){
frame.getTablePanel().getTableModel().getStudents().add(student);
frame.getTablePanel().getTableModel().refresh();
}
}
catch (ParserConfigurationException e1) {
e1.printStackTrace();
}
catch (SAXException e1) {
e1.printStackTrace();
}
catch (FileNotFoundException ex){
JOptionPane.showMessageDialog(frame, "Такого файла не существует");
}
catch (IOException ex){
JOptionPane.showMessageDialog(frame, "Исключение ввода-вывода");
}
catch (Exception ex){
JOptionPane.showMessageDialog(frame, "Ошибка");
}
}
frame.getTablePanel().refreshButtonPanel();
frame.getTablePanel().getTableModel().refresh();
}
} |
|
Обработчик файла xml, шляпошный\
Кликните здесь для просмотра всего текста
| Java |
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
| package controller;
import java.util.ArrayList;
import java.util.List;
import model.Student;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.*;
public class XMLRead extends DefaultHandler{
private List<Student> students;
private Student student;
private String thisElement = "";
public Student getResult(){
return student;
}
@Override
public void startDocument() throws SAXException {
students = new ArrayList<Student>();
}
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
thisElement = qName;
if (thisElement.equals("student")){
student = new Student();
}
}
@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
thisElement = qName;
if (thisElement.equals("student")){
students.add(student);
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (thisElement.equals("cell colName=\"ФИО\"")) {
student.setFio(new String(ch,start,length));
}
if (thisElement.equals("cell colName=\"№ группы\"")) {
student.setGroupNumber(new Integer(new String(ch,start,length)));
}
}
@Override
public void endDocument(){
}
public List<Student> getStudents() {
return students;
}
} |
|
Обработчик совсем не работает, вместо этого в таблице 10 пустых строк создаётся.
Получаем на выводе:
Кликните здесь для просмотра всего текста
| XML |
1
| <?xml version="1.0" encoding="UTF-8" standalone="no"?><students><student><cell colName="ФИО">Гирилюк Павел Александрович</cell><cell colName="№ группы">121701</cell><cell colName="Русский язык">4</cell><cell colName="Литература">7</cell><cell colName="МОИС">7</cell><cell colName="ППвИС">7</cell><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО">Ололош Ололо Ололошенько</cell><cell colName="№ группы">121701</cell><cell colName="Русский язык"/><cell colName="Литература">3</cell><cell colName="МОИС">10</cell><cell colName="ППвИС">9</cell><cell colName="Математика"/><cell colName="Информатика">2</cell></student><student><cell colName="ФИО">Гирилюк Александр Александрович</cell><cell colName="№ группы">121702</cell><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика">9</cell><cell colName="Информатика">7</cell></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student><student><cell colName="ФИО"/><cell colName="№ группы"/><cell colName="Русский язык"/><cell colName="Литература"/><cell colName="МОИС"/><cell colName="ППвИС"/><cell colName="Математика"/><cell colName="Информатика"/></student></students> |
|