0

I use this 3 class for show data from database into JTable.

public class TableContent {

private final Vector<String> headers;
private final Vector<Vector<String>> content;

public TableContent(final Vector<String> headers, final Vector<Vector<String>> content) {
this.headers = headers;
this.content = content;
  }

public Vector<String> headers() {
return headers;
}

public Vector<Vector<String>> content() {
return content;
}

And:

public class TableData {

public TableContent getData() {
Vector<String> headers = new Vector<String>();
Vector<Vector<String>> content = new Vector<Vector<String>>();

try {
    Connection conn = DriverManager.getConnection("");
    Statement statement = conn.createStatement();
    ResultSet rs = statement.executeQuery("Select * from table");

    headers = buildHeaders(rs);
    content = buildContent(rs);

} catch (SQLException e) {
    e.printStackTrace();
}

return new TableContent(headers, content);
 }

private Vector<String> buildHeaders(final ResultSet rs) throws SQLException {
Vector<String> headers = new Vector<String>();

int col = rs.getMetaData().getColumnCount();
for (int i = 1; i <= col; i++) {
    headers.add(rs.getMetaData().getColumnName(i));
    }
return headers;
}

private Vector<Vector<String>> buildContent(final ResultSet rs) throws SQLException {
Vector<Vector<String>> content = new Vector<Vector<String>>();

while (rs.next()) {
    int col = rs.getMetaData().getColumnCount();
    Vector<String> newRow = new Vector<String>(col);

    for (int i = 1; i <= col; i++) {
        newRow.add(rs.getString(i));
    }
    content.add(newRow);
 }
return content;
  }
 }
}

And:

public class TableGUI extends JFrame {
// Create GUI and Show table
 }

Formerly i add my methods to my extended DefaultTableModel Class, Now how can i define this methods and where should do it?

Update:

for e.x I test this method:

public class TableContent {
String dbUrl = "...";

private final Vector<String> headers;
private final Vector<Vector<String>> content;

public TableContent(final Vector<String> hdr, final Vector<Vector<String>> cnt) {
    headers = hdr;
    content = cnt;
}

public Vector<String> headers() {
    return headers;
}

public Vector<Vector<String>> content() {
    return content;
}
public void removeRow(int modelRow, Object rowID) {
    String removeQuery = "delete from table where id=?";
    Connection conn;
    PreparedStatement ps = null;
    try {
        conn = DriverManager.getConnection(...);
        ps = conn.prepareStatement(removeQuery);
        Object idValue = rowID;
        ps.setObject(1, idValue);
        if (ps.executeUpdate() == 1) {
            content.remove(modelRow);
         fireTableRowsDeleted(modelRow, modelRow);   // Error
        }
    } catch (SQLException sqle) {
        sqle.printStackTrace();
    }
}
}

Now in here, Problem is fireTableRowsDeleted(...); !

Problem means that IDE say that cannot resolve methodfireTableRowsDeleted(int,int)`

Sajad
  • 2,273
  • 11
  • 49
  • 92
  • Can you give a bit more details on what you want to achieve? whats your exact question? – micha Sep 02 '13 at 20:43
  • @micha I want to add more methods to my table model. for example i ant to be able to select a row in table and delete or edit it. – Sajad Sep 02 '13 at 20:45
  • @micha I know how do this wirh `JDBC` , but i don't know where should write this methods? in which Class? – Sajad Sep 02 '13 at 20:47

2 Answers2

5

I want to add more methods to my table model. for example i want to be able to select a row in table

This code could be in a ListSelectionListener that is added to the JTable if you want to activate some action on selection of a row/column/cell. If on the other hand you just want to act on the currently selected row and/or column when some other event occurs, such as the press of a button or the right click of a mouse, then you don't even have to add a ListSelectionListener, but rather query the table for the selected row/column, and then convert the row and/or column index to the model using the appropriate convertXxxxIndexToModel(...) method. Be sure to set your table's selection mode appropriately with setSelectionMode(...) as per the tutorials.

and delete or edit it.

The delete code would begin in whatever event that you wish to use to trigger the delete, probably in an AbstractAction class that can be added to a JButton or a pop up menu, or both. Then this Action would call a deleteRow(...) method in your TableModel.

For more specific help, you will want to show us your TableModel code.


Edit
Regarding your update. You state:

Now in here, Problem is fireTableRowsDeleted(...); !

Please understand that we can only understand that which you tell us, and a statement such as "problem is..." tells us close to nothing. What kind of problems are you having? Does it not compile? If not, please show the compiler error message. Does it compile but throw exceptions? If so, please post the full exception? Does it make your monitor put out white smoke? If so, turn of the computer, unplug it and walk away from it. Does it slap you and call you nasty names? What?

And you still haven't posted any table model code. i.e., there is no code for classes that extend any of the TableModels, neither AbstractTableModel nor DefaultTableModel. Your model code cannot work by magic and will need either one of these two for parent classes.


Edit 2
After reading your comments, I'm getting the impression that you believe your TableContent to be your TableModel and are expecting it to be able to compile with method calls such as fireTableRowsDeleted(...) even though your class extends nothing. Some advice:

  • For a class to behave as a TableModel it first must be a TableModel. Translated into OOPs, that means you must use inheritance since this class must satisfy the "is-a" test of object oriented programming.
  • All TableModel classes should at the very least extend the AbstractTableModel class, or it not that class, then a class that ultimately extends from it, since this class contains wiring that is essential for JTables to work with the model.
  • Some classes can get by with extending the DefaultTableModel class which can save you some work since you can use the ready made methods of this class easily.
  • But to extend the DefaultTableModel, you must put all model data into the super class, usually by calling the appropriate super constructor. You cannot have a separate data model nucleus from the DefaultTableModel super class. So I don't think that this will work well for your purposes.
  • Instead you will probably need to extend AbstractTableModel, and then write your own model methods, taking care to fire the appropriate notification methods (they begin with fire***(...)) whenever you change data.
  • Another option is to use a model class that has been created by others if they fulfill your purpose, such as Rob Camick's table model class that works well with SQL databases that can be found on his blog.
  • No matter what you do, it is imperative that you not just read but study the Swing JTable Tutorial as it contains a veritable chit-load of useful and even necessary information that you will need. You can find this and other tutorials at The Really Big Index of Java tutorials.
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • @APoliteBoy: You've posted no code showing your attempt at using a TableModel. That and information on how it's not working would be kind of useful if you need a specific answer. Otherwise about all we can do is give you general advice similar to what I've posted above. – Hovercraft Full Of Eels Sep 02 '13 at 21:34
  • Ok, Problem means that IDE say that `cannot resolve method fireTableRowsDeleted(int,int);` – Sajad Sep 02 '13 at 21:45
  • @APoliteBoy: and that makes perfect sense. You're calling a method that you've declared no where in your class, and it doesn't exist in the parent class (here the parent is Object). I am guessing that you're thinking about extending one of the TableModel classes, but you've yet to extend anything. Again, this won't work by magic -- you have to code the class to extend the parent class. – Hovercraft Full Of Eels Sep 02 '13 at 21:46
  • Are you recommendation me to `Extend DefaultTableModel` my TableContent Class? – Sajad Sep 02 '13 at 21:47
  • @APoliteBoy: see edit to comment above. But as currently written, no you shouldn't extend DefaultTableModel for that class since it appears that you're holding the data in the class and not in the DefaultTableModel super class. You will need to extend AbstractTableModel. And you will need to go through the Swing Table tutorial or go through it again and study the demo programs that are linked to there. – Hovercraft Full Of Eels Sep 02 '13 at 21:48
  • After extending it, My table still needs to re-open to show changes – Sajad Sep 02 '13 at 21:50
  • @APoliteBoy: again, please go through the tutorial and study it step by step. It explains quite well how to use an AbstractTableModel derived class, how to notify the JTable when the model changes. – Hovercraft Full Of Eels Sep 02 '13 at 21:52
  • Google `java JTable tutorial`. First hit. It's just a chapter of the standard Java tutorials, something that should be high up on your bookmark list. – Hovercraft Full Of Eels Sep 02 '13 at 21:56
  • (my view) for why reason you open a close Commection on runtime for every of evens in JTable – mKorbel Sep 03 '13 at 01:27
4

What is this the 10th question on this topic? Why does your posted code to create a TableModel not look like the code I suggested in your 9th posting? In that code example I showed you how to return a TableModel from a method. Instead your code is creating two Vectors and trying to maintain a reference to those Vectors. That is NOT the way to do it. The DefaultTableModel contains the data, you don't need a separate copy of the data. You can access the data in the model by using the getValueAt(..) method.

As I have been suggesting you have two options:

  1. Create a helper class with methods to updated the database and TableModel
  2. Extend the DefaultTableModel to add these methods.

For a helper class you would define a method like:

public void removeRow(DefaultTableModel model, int modelRow)
{
    Object rowID = model.getValueAt(modelRow, theColumn);

    // your code to delete row from database

    if (row delected successfully)
        model.removeRow(modelRow);
}

You don't need the rowID as a parameter because you can get the data from the model by using the getValueAt() method. The idea is to use the methods of the DefaultTableModel to manage the data and not reinvent the wheel. All you are doing is adding code to update the database.

If you want to create a CustomTableModel by extending the DefaultTableModel, then your removeRow() method does not need the DefaultTableModel as a parameter and you can invoke super.removeRow() method of the DefaultTableModel.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Nice, Yes, I want do your second way, extend the DefaultTableModel. I don't want to create table model by method, It's complex for me – Sajad Sep 04 '13 at 15:33
  • I know that i need 3 class to do it. 1th class that retrieves data from database, 2th should create tabled model by extending the `DefaultTableModel` and 3th that is a GUI for show `JTable`. Correct? – Sajad Sep 04 '13 at 15:46
  • So I know that i should not bollix `JDBC` codes in table model class. How should transfer data from my 2th class to my 1th class? By method? – Sajad Sep 04 '13 at 15:48
  • How to load data from database into table model? – Sajad Sep 04 '13 at 15:57
  • 1
    Did you not read my answer? I suggested you need either a helper class for all your database/model related code. Or you need to extend the DefaultTableModel so that all the code is in one class. I showed you how to load data into a model in your previous posting. Why do you even bother to post questions when you don't read the answers??????? – camickr Sep 04 '13 at 18:19