Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Help With JTables

  Asked By: Anpu    Date: May 25    Category: Java    Views: 733
  

I have set up a table which gets two values from a Mysql database.

It reads the data into the table but i am wanting to make it so you
cant select the values and also cant resize or drag the columns. I
have tried everything but with no success. I have shown some code
below. The table.setShowGrid(false) works but none of the other
lines do. Any idea why? Also does anyone know how to make the table
header less "button" like and just text?


JTable table = new JTable(rows,columnHeads);
table.setBackground(Color.blue);
mainPanel.add(table,new XYConstraints(111, 75,200,200));
mainPanel.add(table.getTableHeader(),new XYConstraints(111,
70-table.getRowHeight(),200,table.getRowHeight()+5));
table.setShowGrid(false);
table.setDragEnabled(false);
table.setSelectionBackground(Color.blue);
table.setColumnSelectionAllowed(false);
table.setSelectionBackground(Color.blue);

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Olga Kates     Answered 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);
}
}

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




Tagged: