Disabling User Edits in a JTable Component

Till now you have got the edit facilities in all JTable
in every previous sections but now you will learn a JTable program in
which editing facility is not available. This section tells you, how to disable
the user edits in a JTable component means editing is not allow to user. User
can't edit any cell of JTable according to his/her own requirements.
Description of program:
This program helps you in how to disable user edits in
a JTable components. For this, first of all, you have to create a table
having some data and column with column header. Here the isCellEditable() method
is used to make allows you for editing or not editing. If this method returns
true, you will be able to edit in the JTable and if it returns false, there will
be no editing in any cell of JTable. Try it.
Description of code:
isCellEditable():
This method returns either 'true' or 'false' . If it will return 'true' ,
the cell of JTable is editable otherwise not.
Here is the code of program:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class EditDisable{
JTable table;
public static void main(String[] args) {
new EditDisable();
}
public EditDisable(){
JFrame frame = new JFrame("Disabling User Edits in a JTable!");
JPanel panel = new JPanel();
String data[][] = {{"Vinod","Computer","3"},
{"Rahul","History","2"},
{"Manoj","Biology","4"},
{"Sanjay","PSD","5"}};
String col [] = {"Name","Course","Year"};
DefaultTableModel model = new DefaultTableModel(data,col);
table = new JTable(model){
public boolean isCellEditable(int rowIndex, int colIndex) {
return false; //Disallow the editing of any cell
}
};
JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
JScrollPane pane = new JScrollPane(table);
panel.add(pane);
frame.add(panel);
frame.setSize(500,150);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
Download this example.
Output of program:

|