简体   繁体   中英

Java - Setting JTable as uneditable using a text Area

I've read that i can use text area wherein i'll put my table to it then set the text area as uneditable which will make the table uneditable.

but when i do it, the text area don't show the table that it contains instead it just show the text area itself.

here's how i do it..

    JTable cart;
    DefaultTableModel model;
    JTextArea tArea = new JTextArea();

..

    model = new DefaultTableModel(data,columnName);
    cart = new JTable(model);
    tArea.add(cart);
    tArea.setEditable(false);
    scroll = new JScrollPane(tArea);
    scroll.setBounds(10,130, 700, 400);
    .
    .
    add(scroll);

any idea where I got the wrong part?

As Guillaume Polet already pointed out, I agree that using a JTextArea for setting/changing states in a JTable is inconvenient.

Depending on your requirements I would consider following options:

When you never want the table to be editable you can just override a tables isCellEditable method:

JTable table = new JTable( model )
{
  @Override
  public boolean isCellEditable( int row, int column )
  {
    return false;
  }
};

or subclassing a JTable for some kind of NonEditableTable. Doing it this way has the advantage, whatever model gets added to this table, your table will never be editable. Exactly this can turn out to be a disadvantage as well, because if your editable state is depended on the data it displays you can't change the state of the table anymore.

In this case it might be preferable (as Guillaume Polet already mentioned) to implement your own kind of TableModel no matter if it is extending a DefaultTableModel or AbstractTableModel and override the method in that class to control the behaviour there.

class MyTableModel extends AbstractTableModel
{
  @Override
  public boolean isCellEditable( int rowIndex, int columnIndex )
  {
    if ( /*FILL IN YOUR REQUIREMENTS TO BE EDITABLE*/ )
     return true;

    return false
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM