general_bearbrand
general_bearbrand

Reputation: 827

Set string of a variable from JTable row

I'm trying to get the string in one of my rows in my table and put it in my variable a. How can I do that? Here's my code:

int row = tb_add.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)tb_add.getModel();

String a;
a.setText(model.getValueAt(row, 1).toString());

I'm getting a redline error at setText. I think it's only for objects? How about in a string variable?

Upvotes: 0

Views: 1330

Answers (3)

sakthisundar
sakthisundar

Reputation: 3288

String a  = (String)model.getValueAt(row, 1);

should do it for you. Because values in table model are instances of java.lang.Object. It happens to be a string in your case. If you would like to be more careful in what you are doing, you can do it as below.

Object o = model.getValueAt(row, 1);
  String a = null
  if (o instanceof String) {
     a =  (String) o;
  }

Sometimes just calling toString() method may not really an apt way, as it may return plain toString implementation from Object class even if the value of JTable's column is not of type java.lang.String, but any JComponent or object embedded in the table column.

Note:

a.setText must throw an compilation error for you as there is no such method defined in java.lang.String

Upvotes: 0

Prasad
Prasad

Reputation: 1188

As a is a String variable you should do something like this:

String a = model.getValueAt(row, 1).toString();

Upvotes: 0

Sachin
Sachin

Reputation: 3554

There is no API called as setText(String) in String class. you can use

String a=model.getValueAt(row, 1).toString();

Upvotes: 1

Related Questions