I have created a JTable in one class now i need to use the same table, to set some value in it, in a different class. how shall i use the same JTable in that different class. please tell.
Add a public method in the class that encloses JTable which will set the value and call this method from all the other classes.
The class that contains JTable
must expose this field somehow. Alternately and preferably, the class can provide a method to change some value in the JTable
. The other class must reference the class that contains the JTable
(directly or not):
class A {
private JTable myJTable;
public JTable getMyJTable() {
return myJTable;
}
public void setMyJTableValue(Object value) {
// set the value accordingly
}
}
class B {
private A a;
public void methodWithAccessToA() {
// business logic ...
a.setMyJTableValue(myBusinessValue);
// ...
a.getMyJTable().setValue(myBusinessValue);
}
}
You don't need the second class to have access to the actual table, only to the underlying TableModel
. This can be achieved in many ways:
- A public method
getTableModel()
in the first class which the second can use to get a reference to the model - Both classes keep a reference to the model that is set when their instances are created
- A public method
addValue()
in the fist class that takes the value and adds it to the table model without exposing the model itself. This is the best solution if you only need to perform very specific operations like adding values.
Which method is best suited for you is a matter of design depends on your specific scenario.
If you need to edit values, why don't you work on the Table Model?
JTable.getModel()
(or getTableModel(), I don't remember)
Maybe I am too anal when it comes to encapsulation, but I would not expose the TableModel or the JTable itself usually. In the class containing the JTable I would create methods for adding/removing/setting the values of the JTable. If appropriate I might also have the class with the JTable observe a service which might change its data.