I am trying to make all the cells of a JTable uneditable when double clicked by the user. I have read a lot of forum posts and the general consensus is to create a new table
Earlier today I had the same problem. This solved it for me.
JTable table = new JTable( data, headers ){
public boolean isCellEditable(int row, int column){
return false;
}
};
works great!
Just override the isCellEditable
method of the DefaultTableModel
class. The quick way to do this:
JTable table = new JTable();
DefaultTableModel dtm = new DefaultTableModel(0, 0) {
public boolean isCellEditable(int row, int column) {
return false;
}
};
table.setModel(dtm);
Hello Friend am also working on table please try my code
import javax.swing.table.AbstractTableModel;
public class Table extends AbstractTableModel {
private boolean DEBUG = false;
private String[] columnNames = {" Date Time", " Parameter",
" Barometric Pressure (hPa)", " Temperature (°C)", " Battery Voltage (V)"};
public static Object[][] data = {};
public TableControllerViewdataTabTableModel() {
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
@Override
/**
* The setValueAt.
*/
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
printDebugData();
}
}
/**
* The printDebugData.
*/
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
}
}
}
}
This line creates a new JTable and implicitly creates a DefaultTableModel behind the scenes, one that holds all the correct data needed for the JTable:
storesTable = new JTable(tableData, COL_NAMES);
And this line effectively removes the table model created implicitly above, the one that holds all of the table's data and replaces it with a table model that holds no data whatsoever:
storesTable.setModel(new MyTableModel());
You need to give your MyTableModel class a constructor and in that constructor call the super constructor and pass in the data that you're currently passing to the table in its constructor.
e.g.,
public class MyTableModel extends DefaultTableModel {
public MyTableModel(Object[][] tableData, Object[] colNames) {
super(tableData, colNames);
}
public boolean isCellEditable(int row, int column) {
return false;
}
}
Then you can use it like so:
MyTableModel model = new MyTableModel(tableData, COL_NAMES);
storesTable = new JTable(model);