tags:

views:

67

answers:

5

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.

A: 

Add a public method in the class that encloses JTable which will set the value and call this method from all the other classes.

Boris Pavlović
A: 

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);
   }

}
bruno conde
Can the person that downvoted this give me a reason?
bruno conde
I didnt, but exposing the JTable seems like a bad idea. Encapsulation and so forth :)
willcodejavaforfood
I also said that "Alternately and preferably, the class can provide a method to change some value in the JTable" and Encapsulation is required when you go to getJTable() or getJTableModel().
bruno conde
thanks for helping..but when i am using this way it is giving error that getMyJTable is an unknown symbol for Class B. what shall i do now please tell.
+2  A: 

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.

Michael Borgwardt
A: 

If you need to edit values, why don't you work on the Table Model?

JTable.getModel()

(or getTableModel(), I don't remember)

michelemarcon
+1  A: 

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.

willcodejavaforfood
+1 on the observer idea
akf