Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: Anpu Massri   on May 25 In Java Category.

  
Question Answered By: Olga Kates   on May 25

To make the user totally can't select/edit the values,
what you can do is to set  the setEnabled() to false.
The other way is you can override the isCellEditable.
And to change the header or any cell of the table  style,
override the cell renderer.

Below is the example:

public MyTable() {
String[] header = {"H1", "H2", "H3"};
String[][] data  = {{"a1", "a2", "a3"},
{"b1", "b2", "b3"},
{"b1", "b2", "b3"}};

// create the table model
DefaultTableModel model = new  Model(data, header);
// create the renderer
DefaultTableCellRenderer render = new Renderer();

JTable table = new JTable();
// set the model to the table
table.setModel(model);
table.setShowGrid(false);
table.setDragEnabled(false);
table.setSelectionBackground(Color.blue);

JTableHeader tableHeader = table.getTableHeader();
tableHeader.setReorderingAllowed(false);
tableHeader.setResizingAllowed(false);
tableHeader.setDefaultRenderer(render);

JScrollPane sp = new JScrollPane();
sp.getViewport().add(table);
getContentPane().add(sp);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

private class Model extends DefaultTableModel {
public Model(String[][] data, String[] header) {
super(data, header);
}

// To disable cell editing. By specifying the row
// and col, you can control any single cell to be editable
// or not
public boolean isCellEditable(int row, int col) {
return false;
}
}

private class Renderer extends DefaultTableCellRenderer {
public Renderer() {
// change the border style
this.setBorder(null);
}
}

Share: 

 
 
Didn't find what you were looking for? Find more on Help With JTables Or get search suggestion and latest updates.


Tagged: