Привет всем!
Помогите разобраться, что я делаю не так.Пытаюсь динамически добавить
строку в JTable используя модель MVC.Вся проблема заключается в методе insertRow.
Когда я вызываю этот метод,то выскакивает Exception:
at JDBCAdapter.getValueAt(JDBCAdapter.java:191)
......
......
Привожу код доработанного sun-го класса JDBCAdapter:
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.
137.
138.
139.
140.
141.
142.
143.
144.
145.
146.
147.
148.
149.
150.
151.
152.
153.
154.
155.
156.
157.
158.
159.
160.
161.
162.
163.
164.
165.
166.
167.
168.
169.
170.
171.
172.
173.
174.
175.
176.
177.
178.
179.
180.
181.
182.
183.
184.
185.
186.
187.
188.
189.
190.
191.
192.
193.
194.
195.
196.
197.
198.
199.
200.
201.
202.
203.
204.
205.
206.
207.
208.
209.
210.
211.
212.
213.
214.
215.
216.
217.
218.
219.
220.
221.
222.
223.
224.
225.
226.
227.
228.
229.
230.
231.
232.
233.
234.
235.
236.
237.
238.
239.
240.
241.
242.
243.
244.
245.
246.
247.
248.
249.
250.
251.
252.
253.
254.
255.
256.
257.
import java.util.Vector;
import java.sql.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.event.TableModelEvent;
import java.util.Properties;
public class JDBCAdapter extends AbstractTableModel {
Connection connection;
Statement statement;
ResultSet resultSet;
String[] columnNames = {};
Vector rows = new Vector();
ResultSetMetaData metaData;
//*********************************************************************************************//
public JDBCAdapter(String url, String driverName,Properties prop) {
try {
Class .forName(driverName);
System.out.println("Opening db connection");
connection = DriverManager.getConnection(url, prop);
statement = connection.createStatement();
}
catch (ClassNotFoundException ex) {
System.err.println("Cannot find the database driver classes.");
System.err.println(ex);
}
catch (SQLException ex) {
System.err.println("Cannot connect to this database.");
System.err.println(ex);
}
}
//*********************************************************************************************//
public void executeQuery(String query) {
if (connection == null || statement == null ) {
System.err.println("There is no database to execute the query.");
return ;
}
try {
resultSet = statement.executeQuery(query);
metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
columnNames = new String[numberOfColumns];
// Get the column names and cache them.
// Then we can close the connection.
for ( int column = 0 ; column < numberOfColumns; column++) {
columnNames[column] = metaData.getColumnLabel(column+ 1 );
}
// Get all rows.
rows = new Vector();
while (resultSet.next()) {
Vector newRow = new Vector();
for ( int i = 1 ; i <= getColumnCount(); i++) {
newRow.addElement(resultSet.getObject(i));
}
rows.addElement(newRow);
}
// close(); Need to copy the metaData, bug in jdbc:odbc driver.
fireTableChanged( null ); // Tell the listeners a new table has arrived.
}
catch (SQLException ex) {
System.err.println(ex);
}
}
//*********************************************************************************************//
public void close() throws SQLException {
System.out.println("Closing db connection");
resultSet.close();
statement.close();
connection.close();
}
//*********************************************************************************************//
protected void finalize() throws Throwable {
close();
super .finalize();
}
//*********************************************************************************************//
//////////////////////////////////////////////////////////////////////////
//
// Implementation of the TableModel Interface
//
//////////////////////////////////////////////////////////////////////////
// MetaData
//*********************************************************************************************//
public String getColumnName( int column) {
if (columnNames[column] != null ) {
return columnNames[column];
} else {
return "";
}
}
//*********************************************************************************************//
public Class getColumnClass( int column) {
int type;
try {
type = metaData.getColumnType(column+ 1 );
}
catch (SQLException e) {
return super .getColumnClass(column);
}
switch (type) {
case Types. CHAR :
case Types.VARCHAR:
case Types.LONGVARCHAR:
return String. class ;
case Types.BIT:
return Boolean . class ;
case Types.TINYINT:
case Types.SMALLINT:
case Types.INTEGER:
return Integer. class ;
case Types.BIGINT:
return Long . class ;
case Types. FLOAT :
case Types. DOUBLE :
return Double . class ;
case Types.DATE:
return java.sql.Date. class ;
default :
return Object. class ;
}
}
//*********************************************************************************************//
public boolean isCellEditable( int row, int column) {
try {
return metaData.isWritable(column+ 1 );
}
catch (SQLException e) {
return false;
}
}
//*********************************************************************************************//
public int getColumnCount() {
return columnNames.length;
}
// Data methods
//*********************************************************************************************//
public int getRowCount() {
return rows.size();
}
//*********************************************************************************************//
public Object getValueAt( int aRow, int aColumn) {
Vector row = (Vector)rows.elementAt(aRow);
return row.elementAt(aColumn);
}
//*********************************************************************************************//
public String dbRepresentation( int column, Object value) {
int type;
if (value == null ) {
return "null";
}
try {
type = metaData.getColumnType(column+ 1 );
}
catch (SQLException e) {
return value.toString();
}
switch (type) {
case Types.INTEGER:
case Types. DOUBLE :
case Types. FLOAT :
return value.toString();
case Types.BIT:
return (( Boolean )value).booleanValue() ? "1" : "0";
case Types.DATE:
return value.toString(); // This will need some conversion.
default :
return "\'"+value.toString()+"\'";
}
}
//*********************************************************************************************//
public void setValueAt(Object value, int row, int column) {
try {
String tableName = metaData.getTableName(column+ 1 );
if (tableName == null ) {
System.out.println("Table name returned null.");
}
String columnName = getColumnName(column);
String query =
"update "+tableName+
" set "+columnName+" = "+dbRepresentation(column, value)+
" where ";
for ( int col = 0 ; col<getColumnCount(); col++) {
String colName = getColumnName(col);
if (colName.equals("")) {
continue ;
}
if (col != 0 ) {
query = query + " and ";
}
query = query + colName +" = "+
dbRepresentation(col, getValueAt(row, col));
}
//System.out.println(query);
PreparedStatement ps = connection.prepareStatement(query);
ps.executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
Vector dataRow = (Vector)rows.elementAt(row);
dataRow.setElementAt(value, column);
}
//*********************************************************************************************//
public void removeRow( int row){
rows.removeElementAt(row);
rows.setSize(getRowCount());
fireTableRowsDeleted(row,row);
}
//*********************************************************************************************//
public void insertRow(Object rowData){
rows.add(rowData);
fireTableRowsInserted(rows.size(),rows.size());
}
//*********************************************************************************************//
private void justifyRows( int from, int to) {
rows.setSize(getRowCount());
}
//*********************************************************************************************//
public void executeUpdates(String query) {
if (connection == null || statement == null ) {
System.err.println("Нет соединения с БД!");
return ;
}
try {
System.out.println(query);
PreparedStatement ps = connection.prepareStatement(query);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
//*********************************************************************************************//
}
И вот код класса в котором исп.JDBCAdapter:
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.
import sun.awt.VerticalBagLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Dimension;
import interbase.interclient.*;
import java.util.*;
import java.sql.*;
public class Ops{
private static String DatabaseURL= new String("jdbc:interbase://localhost/E:/WorkWith/Java/Systems/GuiModule(learn)/Mine2.GDB");
private static String driverName = "interbase.interclient.Driver";
private static Properties prop= new Properties();
public static void main(String[] args){
JFrame frame= new JFrame("Table Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JDBCAdapter dt= new JDBCAdapter(DatabaseURL,driverName,prop);
//final ExtTable dt=new ExtTable(DatabaseURL,driverName,prop);
dt.executeQuery("Select * from RUS");
//Create the table
final JTable tableView = new JTable(dt);
JScrollPane scrollpane = new JScrollPane(tableView);
tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tableView.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JButton btn1= new JButton("Удалить");
btn1.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
int curRow=tableView.getSelectedRow();
dt.removeRow(curRow);
tableView.repaint();
}
});
JButton btn2= new JButton("Вставить");
btn2.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object dats;
dats="A1";
//Что-то не работает
dt.insertRow(dats);
tableView.repaint();
}
});
frame.getContentPane().add(scrollpane);
frame.getContentPane().add(btn1);
frame.getContentPane().add(btn2);
frame.getContentPane().setLayout( new FlowLayout());
frame.pack();
frame.setBounds( 200 , 200 , 750 , 500 );
frame.setVisible(true);
}
}
В чем ошибка реализации метода insertRow класса JDBCAdapter?
Заранее спасибо.