This question already has answers here:
How to make a JTable non-editable
(7 answers)
Closed 1 year ago.
When a JTable component is created, cell editing is enabled by default. How can I prevent the user from editing the content of a JTable?
You can create a JTable using following code:
JTable jTable = new JTable() {
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column) {
return false;
};
};
Basically what we are doing here is overriding isCellEditable and always returning false from it. This will make a non editabe JTabel.
A JTable uses an AbstractTableModel object. This is the thing you pass into the constructor of the JTable. You can write your own AbstractTableModel as follows
public class MyTableModel extends AbstractTableModel {
public boolean isCellEditable(int row, int column){
return false;
}
}
and then initialize your JTable as
JTable myTable = new JTable(new MyTableModel());
myTable.setDefaultEditor(Object.class, null);
Have you tryed simply:
JTable table = new JTable();
table.setEnabled(false);
About JComponent.setEnabled(boolean) it sayes:
Sets whether or not this component is enabled. A component that is enabled may respond to user input, while a component that is not enabled cannot respond to user input. Some components may alter their visual representation when they are disabled in order to provide feedback to the user that they cannot take input.
When it comes to JTable it doesnt seem to give any visual feedback at all. With the perk of still being able to click on the column headers. And in my implementation the application could still change the contents of the cells.
Hi I'm working a lot on java so I'm gonna give you my way:
There are two possibilities the first under netbeans. Go to customize code and make it like this:
JTArticleJPAddArrticle = new javax.swing.JTable();
JTArticleJPAddArrticle.setBackground(new java.awt.Color(204, 204, 255));
JTArticleJPAddArrticle.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Reference","Libellé","Marque","Prix d'achat","Prix de vente","Quantité","Total","Etat"
}
){
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
});
jScrollPane8.setViewportView(JTArticleJPAddArrticle);
My other way is to do it is to make an instance of the table model. This is the second way:
model=new DefaultTableModel(head, 0){
#Override
public boolean isCellEditable(int i, int i1) {
return false; //To change body of generated methods, choose Tools | Templates.
}
};
jtable.setmodel(model);
Enjoy this is working well for me. All I want to do is help you guys out because I was helped out a lot earlier.
Well on netbeans you can right click on the table and click on table contents, then you go to the column tab and uncheck the "Editable" checkbox. Greetings!!
I know I am late but hope someone get use of this. You can simple add mouse listener like this:
jtable.addMouseListener( new MouseAdapter () {
#Override
public void mouseClicked ( MouseEvent e ) {
columnIndex = replacedAssets.getSelectedColumn ();
System.out.println ( "Double click on jtable" );
if ( columnIndex == 1 || columnIndex == 2 ) {
JOptionPane.showMessageDialog ( parent , "Editing this Field may cause error in the data." , "Error Edit Not Permitted For This Field" , JOptionPane.ERROR_MESSAGE );
}
}
});
this code prevent editing the columns of indexes 1 and 2 you can remove the if condition to make this work for all columns.
tm = new javax.swing.table.DefaultTableModel()
{
public Class<?> getColumnClass(int column)
{
switch(column)
{
case 0:
return String.class;
case 1:
return String.class;
case 2:
return String.class;
case 3:
return String.class;
case 4:
return String.class;
case 5:
return String.class;
case 6:
return String.class;
case 7:
return String.class;
case 8:
return String.class;
case 9:
return String.class;
case 10:
return String.class;
case 11:
return Boolean.class;
default:
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int column) {
/* Set the 11th column as editable and rest non-
editable */
if(column==11){
return true;
}else{
//all other columns to false
return false;
}
}
};
table = new javax.swing.JTable(tm);
In this method "isCellEditable" we can enable and disable user edit for particular column. In this case enable column=11 and disable rest of the column
Related
I want to make my JTable Non-editable
As I use following code to set rows using SetModel():
jTable1.setModel(DbUtils.resultSetToTableModel(rs)); //Resultset is added as each row using r2xml JAR file
I cant use follwing code:
jTable1.setModel(new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
});
Because we cannot use two setModel() for jTable.
How to overcome this problem?
I want to setresult and make jTable Noneditable.
Here are 2 ways to achieve that:
Create and use your own TableModel implementation which forwards all calls to the table model returned by DbUtils except for isCellEditable() in which you can return always false hence disabling editing. Your own table model could get the model returned by DbUtils as a constructor argument for example.
You can extend JTable and override its isCellEditable() method to return false (by default it calls the model's isCellEditable() method). Maybe other Swing enthusiasts will see this as an evil hack, but it is the simplest solution to your problem here.
Elaborating method #1
This is how you can create your model:
class MyModel implements TableModel {
private final TableModel m;
public MyModel(TableModel m) {
this.m = m;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
// This is how we disable editing:
return false;
}
// The rest of the methods just forward to the other model:
#Override
public int getRowCount() {
return m.getRowCount();
}
#Override
public int getColumnCount() {
return m.getColumnCount();
}
// ...and all other methods which I omit here...
}
And this is how you can use it:
jTable1.setModel(new MyModel(DbUtils.resultSetToTableModel(rs)));
Elaboration of method #2
Extending JTable can even be an anonymous class:
JTable jtable1 = new JTable() {
#Override
public boolean isCellEditable(int row, int column) {
// This is how we disable editing:
return false;
}
};
And using it:
// You can set any model, the table will not be editable because we overrode
// JTable.isCellEditable() to return false therefore the model will not be asked
// if editable.
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
you can use this code for make non editable jTable
simply you write one line in your program
jTable.disable();
The program in general is 3 arrays of a custom objects , with a JTable representing each array. I have a custom renderer and tablemodel. The custom object has inside it an object which is every visual element.
When I remove a row from 1 table and replace , rerender it as it is empty it renders perfectly , but when I add a new row to the table it renders properly JTextField and JLabel , but renders JButtons from previous object.
Table model
public class PositionTableModel extends AbstractTableModel
{
private List<kosilkshik.Position> local;
public PositionTableModel(List<kosilkshik.Position> list)
{
local = list;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return true;
}
#Override
public int getRowCount(){return local.size();}
#Override
public int getColumnCount() {return 24;}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
kosilkshik.Position pos = local.get(rowIndex);
switch (columnIndex)
{
case 0:
return pos.view.symbols.get(0);
case 1:
return pos.view.ratios.get(0);
case 2:
return pos.view.symbols.get(1);
case 3:
return pos.view.ratios.get(1);
case 4:
if(pos.view.symbols.size()>2)
{
return pos.view.symbols.get(2);
}else{return null;}
case 5:
if(pos.view.symbols.size()>2)
{
return pos.view.ratios.get(2);
}else{return null;}
case 6:
if(pos.view.symbols.size()>3)
{
return pos.view.symbols.get(3);
}else{return null;}
case 7:
if(pos.view.symbols.size()>3)
{
return pos.view.ratios.get(3);
}else{return null;}
case 8:
return pos.view.name;
case 9:
return pos.view.qt;
case 10:
return pos.view.current;
case 11:
return pos.view.buy;
case 12:
return pos.view.sell;
case 13:
return pos.view.bid;
case 14:
return pos.view.avg;
case 15:
return pos.view.ask;
case 16:
return pos.view.mkt;
case 17:
return pos.view.p;
case 18:
return pos.view.flip;
case 19:
return pos.view.invert;
case 20:
return pos.view.control;
case 21:
return pos.view.control1;
case 22:
return pos.view.control2;
case 23:
return pos.view.control3;
default:
return null;
}
}
}
TableRender does not have any caching manually added.
Method for removing rows from table
AbstractTableModel m =(AbstractTableModel)tableS.getModel();
m.fireTableRowsDeleted(row,row);
Method for inserting rows:
AbstractTableModel m =(AbstractTableModel)tableS.getModel();
m.fireTableRowsInserted(0, suggested.size()-1);
Method for removing rows from table...,
Method for inserting rows...
Those two methods should be part of the custom TableModel, not part of your application code. It is the responsibility of the TableModel to notify the table when the data changes. So you need to create method for you model like "addRow(...)" and "removeRow(...)".
Make sure the "row" values you pass to the fireXXX methods are correct. The DefaultTableModel implements addRow(...) and removeRow(...) method, so check out the source code of the DefaultTableModel to see how that code works.
This question already has answers here:
JTable with editable checkbox
(2 answers)
Closed 8 years ago.
hi my java swing project have a table with last column is boolean values..i changed it into chceckbox.but i need to bind event on it and know if it is check or not..!!
Below Code works it is showing checkbox
retunTable=new JTable(model){
private static final long serialVersionUID = 1L;
/*#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
#Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return Object.class;
case 1:
return Object.class;
case 2:
return Object.class;
case 3:
return Object.class;
default:
return Boolean.class;
}
}
};
i dont know where to put addActionListener..!!
Help needed..!!
i dont know where to put addActionListener..!!
TableCellEditort/Renderer isn't real JComponent
override setValueAt in XxxTableModel
I woudln't suggest to use custom TableCellEditort/Renderer for this job
override getColumnClass in XxxTableModel instead for subclassing JTable
Hi I have an arraylist of a class I created called Pets which has the variables below
private String name;
private String species;
private int age;
I wanted to display this arraylist into a jTable and I did that succesfully by using defaultTableModel and calling setModel().
However I needed to add a sorting and filtering function for the Jtable. I took a look at the java tutorials were they were creating a subclass of AbstractTableModel in order to sort and filter. However they were using arrays to store the data. So I tried modifying the code to use an arraylist isntead but Im stuck with this method
public Object getValueAt(int row, int col) {
return data[row][col];
}
How do I get all the values from one object from th arraylist?
Any help will be greatly appreciated. Thanks in advance.
Does your ArrayList hold a row that is it's own type of object? If so, and if your ArrayList is a generic ArrayList<RowItem> then you could do something like:
#Override
public Object getValueAt(int row, int col) {
if (row > getRowCount()) {
// throw an exception
}
RowItem rowItem = rowItemList.get(row);
switch (col) {
case 0:
return rowItem.getName();
case 1:
return rowItem.getLastSpecies();
case 2:
return rowItem.getAge();
}
return null; // or throw an exception
}
You can try this:
public Object getValueAt(int row, int col) {
switch(col) {
case 0:
return ((Pets)data.get(row)).getName();
case 1:
return ((Pets)data.get(row)).getSpecies();
case 2:
return ((Pets)data.get(row)).getAge();
}
return null;
}
I have an unusual situation where I need to have a JTree with each node containing 2 checkboxes and a label (with the ability to add a listener to tell when any of the potential checkboxes are checked). I also need the root node to have the same layout (which I'm assuming means creating a JPanel with 2 JCheckBoxes and a JLabel), with the ability to select all the checkboxes down the tree if one in the root is checked.
Any guidance or examples? I've checked out previous questions on here and associated examples...some of which allowed me to get to the point of having the tree "look" but without giving me a direction for implementing the action behind it.
Thanks!
This might be a good time to look at the old JTreeTable code, which will give you a tree rendered in the first column, and the freedom to render the cells for each column to the right of the tree node as you wish, in your case putting in checkboxes and a label, and allowing you to have TableCellEditors working with your JTable as you are used to. A warning is that, while the code in that link works, it is a little convoluted.
There is an alternative. I have demoed below a Tree Table implementation that is supposed to be better, called Outline, provided by NetBeans (though you don't need to develop with the NetBeans IDE, you just need the jar). This article indicates how easy it is to be to get started.
I was able to mock up a quick example of the Outline tree table in Eclipse (with the org-netbeans-swing-outline.jar imported to my project) in about 30 minutes (I am slow at typing):
private void buildFrame() {
frame = new JFrame("Demo");
frame.setSize(300, 300);
addStuffToFrame();
frame.setVisible(true);
}
private void addStuffToFrame() {
MyTreeNode top = new MyTreeNode("top");
createNodes(top);
DefaultTreeModel model = new DefaultTreeModel(top);
//here are the netBeans tree table classes
OutlineModel outlineModel =
DefaultOutlineModel.createOutlineModel(model, new MyRowModel());
Outline outline = new Outline();
outline.setRootVisible(true);
outline.setModel(outlineModel);
frame.getContentPane().add(new JScrollPane(outline));
}
private void createNodes(MyTreeNode top) {
MyTreeNode child = new MyTreeNode("child 2");
top.add(new MyTreeNode("child 1"));
child.add(new MyTreeNode("g-child1"));
child.add(new MyTreeNode("g-child2"));
child.add(new MyTreeNode("g-child3"));
top.add(child);
top.add(new MyTreeNode("child3"));
top.add(new MyTreeNode("child4"));
}
I create a TreeNode to hold the Booleans that will interoperate well with the JTable's built-in checkbox rendering mechnanism.
public class MyTreeNode extends DefaultMutableTreeNode {
Boolean data1 = null;
Boolean data2 = null;
String name = null;
MyTreeNode (String name) {
this.name=name;
}
void setData1(Boolean val) {data1=val;}
void setData2(Boolean val) {data2=val;}
Boolean getData1() {return data1;}
Boolean getData2() {return data2;}
String getName() {return name;}
}
The netBeans RowModel is the key to making this a table instead of a simple JTree:
public class MyRowModel implements RowModel {
public Class getColumnClass(int col) {
switch (col) {
case 0: return String.class;
case 1: return Boolean.class; //these return class definitions will
case 2: return Boolean.class; //trigger the checkbox rendering
default:return null;
}
}
public int getColumnCount() {
return 3;
}
public String getColumnName(int col) {
return "";
}
public Object getValueFor(Object node, int col) {
MyTreeNode n = (MyTreeNode)node;
switch (col) {
case 0: return n.getName();
case 1: return n.getData1();
case 2: return n.getData2();
default:return null;
}
}
public boolean isCellEditable(Object node, int col) {
return col > 0;
}
public void setValueFor(Object node, int col, Object val) {
MyTreeNode n = (MyTreeNode)node;
if (col == 1) {n.setData1((Boolean)val);}
else if (col == 2) {n.setData2((Boolean)val);}
//EDIT: here is a recursive method to set all children
// selected for one of the two checkboxes as it is
// checked by the parent
for (Enumeration children = n.children();
children.hasMoreElements(); ) {
MyTreeNode child = (MyTreeNode) children.nextElement();
setValueFor(child, col, val);
}
}
}
here is the finished, albeit simplistic, product:
alt text http://img17.imageshack.us/img17/6643/picture1hz.png
I have updated the setValueFor method to iterate over a node's children and set the checkboxes as selected or deselected when a parent has been modified.
Take a look at http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm
It wasn't clear where the buildFrame(), addStuffToFrame() and createNodes() methods go. I put them all into an OutlineJFrame class I created that extends JFrame, and deleted the 'frame.' preface where-ever it appeared. Then in my project's main() method, it just created one of those OutlineJFrame objects and set its visible to true. When it ran, I got a resizable but empty window. Where were the rows? Where were the nodes?
Then I asked Geertjan, the NetBeans guru, what I was doing wrong, and he sent me a re-write. But it had the same behaviour.
But I know that my java is fine, because another demo project I did (FileTreeJFrame) displays outline.java objects just fine.