I want to make my JTable unEditable but i want to add JButton to to it and the column of the button must be editable for the press event so how can i make this only column editable?
here is my table model code:
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new String[]{
"IDemp",
"empNumber",
"Fname","Lname",
"BirthDate",
"Address",
"email",
"Button" }
);
//TableCellRenderer buttonRenderer = new JTableButtonRenderer();
for(int i=0;i<emps1.size();i++) {
model.addRow(new Object[]{String.format("%d",emps1.get(i).getIDemp()),
String.format("%d",emps1.get(i).getEmpNumber()),emps1.get(i).getFname(),
emps1.get(i).getLname(),emps1.get(i).getBirthDate(),
emps1.get(i).getAddress(), emps1.get(i).getEmail().getEmailAddress()});
}
and here is my jtable:
JTable emps=new JTable(model);
emps.getColumn("Button").setCellRenderer(new ButtonRenderer());
emps.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));
How could I make the "Button" column editable and the others not?
*And if you have better way to add JButton to the JTable it will be great."
You need to extends the AbstractTableModel and override isCellEditable like this:
public class MyTableModel extends AbstractTableModel {
public boolean isCellEditable(int row, int col) {
if (col== columnIndex) { //columnIndex: the column you want to make it editable
return true;
} else {
return false;
}
}
}
Related
I have a jtable with the first column having jbuttons. However when i try to click the button nothing happens. Hovering over the button also doesn't change it's shade to show that it's clickable..
I am running this from within a Java Applet.
I am using the Button Column Class from here:
http://www.camick.com/java/source/ButtonColumn.java
and here is the code i inserted myself
tablemodel = new DefaultTableModel();
//PnlThinClientTable.COLUMNS is an array of strings with the titles of the columns
tablemodel.setColumnIdentifiers(PnlThinClientTable.COLUMNS);
JTable table = new JTable(tablemodel);
table.setEnabled(false);
table.setDefaultRenderer(table.getColumnClass(5), new CustomTblCellRenderer());
table.setBackground(Color.WHITE);
Action wakeUpRow = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e){
JTable table = (JTable)e.getSource();
int modelRow = Integer.valueOf( e.getActionCommand() );
System.out.println("Action Performed");
}
};
// Main.hm_language.get(Language.WAKE_ON_LAN) returns the title of the column i'm interested in
table.getColumn(Main.hm_language.get(Language.WAKE_ON_LAN)).setCellRenderer(new ButtonColumn(table,wakeUpRow,0));
table.getColumn(Main.hm_language.get(Language.WAKE_ON_LAN)).setCellEditor(new ButtonColumn(table, wakeUpRow, 0));
Thanks to #alex2410 for the solution
I had to make sure the cell was Editable
this can be done by either extending the Table upon declaration and overriding the isCellEditable(int row, int col): boolean method,
or in my case I overrode isCellEditable(EventObject e):boolean in the Cell Editor which I apply to the column,
hence the snippet within the Cell Editor I am using would be
#Override
public boolean isCellEditable(EventObject e){
return true;
}
This is as all cells to which the editor is applied need to be editable, as they are all buttons in my case.
Answering to the comment of "how to make 1st column editable" here's how
class MyTableModel extends AbstractTableModel {
public boolean isCellEditable(int row, int col) {
if (col == 1) {
return true;
} else {
return false;
}
}
}
Anyway I leave How to Use Tables Documentation in case it's needed.
And also this post that could help: How to make a table (Jtable) not editable
My problem is that I want to have a itemSateChanged listener on a combo box which is inside a jTable. When I change the values of the combo box I want data added to a cell in the respected row of the jTable.
This is the code where the combo box is created.
public void setUpSectionColumn(JTable table, TableColumn statusColumn) {
//Set up the editor for the sport cells.
JComboBox comboBox = new JComboBox();
comboBox.addItem("Lending");
comboBox.addItem("Childen Lending");
comboBox.addItem("Reference");
comboBox.addItem("Special Collection");
statusColumn.setCellEditor(new DefaultCellEditor(comboBox));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
statusColumn.setCellRenderer(renderer);
}
This is the method I have come up with for the listener which does not work.
public void fillTable2() {
jTable2.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent evt) {
int row = jTable2.getSelectedRow();
String section;
if (row == -1) {
section = "Lending";
} else {
section = jTable2.getValueAt(row, 3).toString();
}
int accessNo = bdao.getLastAccessNo(section);
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
Object[] rowdata = {Integer.toString(accessNo), "", ""};
model.addRow(rowdata);
}
});
}
As discussed here, you can use a JComboBox as a TableCellEditor. There's an example here using DefaultCellEditor.
i´m trying to put a checkbox in a column in my table...but i shows de boolean value, when i click over the cell, it shows the checkbox and sooner show the boolean value...
public class Tabela {
private JTable tabela;
private JCheckBox checkbox;
public Tabela(Object[][] linhas, String[] nomeColunas) {
this.tabela = new JTable();
this.tabela.setModel(new DefaultTableModel(linhas, nomeColunas));
this.checkbox = new JCheckBox();
this.tabela.setFillsViewportHeight(true);
this.tabela.getColumn("Selecione").setCellEditor(
new DefaultCellEditor(checkbox));
}
public JTable getTabela() {
return tabela;
}
}
So what´s wrong with my code?
I create seppareted my form, table and panel...
You must override getColumnClass(...) and return Boolean.class for the column that should display the checkboxes. The data model will need to hold Boolean objects for that column as well.
How to make a JTable non-editable? I don't want my users to be able to edit the values in cells by double-clicking them.
You can override the method isCellEditable and implement as you want
for example:
//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
table.setModel(tableModel);
or
//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
//Only the third column
return column == 3;
}
};
table.setModel(tableModel);
Note for if your JTable disappears
If your JTable is disappearing when you use this it is most likely because you need to use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor instead.
//instance table model
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
table.setModel(tableModel);
table.setDefaultEditor(Object.class, null);
just add
table.setEnabled(false);
it works fine for me.
You can use a TableModel.
Define a class like this:
public class MyModel extends AbstractTableModel{
//not necessary
}
actually isCellEditable() is false by default so you may omit it. (see: http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html)
Then use the setModel() method of your JTable.
JTable myTable = new JTable();
myTable.setModel(new MyModel());
If you are creating the TableModel automatically from a set of values (with "new JTable(Vector, Vector)"), perhaps it is easier to remove editors from columns:
JTable table = new JTable(my_rows, my_header);
for (int c = 0; c < table.getColumnCount(); c++)
{
Class<?> col_class = table.getColumnClass(c);
table.setDefaultEditor(col_class, null); // remove editor
}
Without editors, data will be not editable.
I used this and it worked : it is very simple and works fine.
JTable myTable = new JTable();
myTable.setEnabled(false);
create new DefaultCellEditor class :
public static class Editor_name extends DefaultCellEditor {
public Editor_name(JCheckBox checkBox) {
super(checkBox);
}
#Override
public boolean isCellEditable(EventObject anEvent) {
return false;
}
}
and use setCellEditor :
JTable table = new JTable();
table.getColumn("columnName").setCellEditor(new Editor_name(new JCheckBox()));
I want to put individual JComboBoxes into each cells of a JTable. ie. The JComboBox content is not identical for each cell.
I basically would like to be able to just call the following code to add a row of JComboBox into the JTable. Anyone has any idea? Thanks
JComboBox cb1 = new JComboBox(...);
JComboBox cb2 = new JComboBox(...);
model.addRow(new Object[] {"Row name", cb1, cb2} );
JComboBox cb3 = new JComboBox(...);
JComboBox cb4 = new JComboBox(...);
model.addRow(new Object[] {"Row name 2", cb3, cb4} );
The closest example code I can find is as follows. But it is for where JComboBox content is identical for the individual column. Not the solution I need.
TableColumn col = table.getColumnModel().getColumn(vColIndex);
col.setCellEditor(new MyComboBoxEditor(values));
where
public class MyComboBoxEditor extends DefaultCellEditor {
public MyComboBoxEditor(String[] items) {
super(new JComboBox(items));
}
}
Extend JTable with this code:
#Override
public TableCellEditor getCellEditor(int row, int column) {
Object value = super.getValueAt(row, column);
if(value != null) {
if(value instanceof JComboBox) {
return new DefaultCellEditor((JComboBox)value);
}
return getDefaultEditor(value.getClass());
}
return super.getCellEditor(row, column);
}
This will create a unique JComboBox cell editor for each combo box you get the a value for.
I am sure this will solve your problem. Mention in which column you need to set the combo box in .getColumn(int column)
private void addComboToTable(JComboBox combo) {
TableColumn gradeColumn = YourTable.getColumnModel().getColumn(0);
JComboBox comboBox = combo;
comboBox.removeAllItems();
try {
comboBox.addItem("Item 1");
comboBox.addItem("Item 2");
comboBox.addItem("Item 3");
} catch (NullPointerException e) {
} catch (Exception e) {
e.printStackTrace();
}
gradeColumn.setCellEditor(new DefaultCellEditor(comboBox));
}
You need to override:
Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
...in TableCellEditor. The value passed in to this method is what you can put in your JComboBox. That means that the 'value' for that particular cell needs to be something that can be translated into a collection. It could potentially just be a List of objects or it could be a POJO with fields that could be made into a JComboBox.
So just edit MyComboBoxEditor to override that method and change your model to allow for an Object that actually represents several other objects.
The JComboBox content is render identical for each row selection because
the JTable does not offer the capability to have more than one editor per column.
You have to extend the JTable class to support an additional selection for rows.
This article explains it very well:
http://www.javaworld.com/javaworld/javatips/jw-javatip102.html
In addition to cellEditor it is necessary to do the cellRenderer to paint the combobox in the cell, look at this:
public void example(){
TableColumn tmpColum =table.getColumnModel().getColumn(1);
String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" };
JComboBox comboBox = new JComboBox(DATA);
DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox);
tmpColum.setCellEditor(defaultCellEditor);
tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox));
table.repaint();
}
/**
Custom class for adding elements in the JComboBox.
*/
class CheckBoxCellRenderer implements TableCellRenderer {
JComboBox combo;
public CheckBoxCellRenderer(JComboBox comboBox) {
this.combo = new JComboBox();
for (int i=0; i<comboBox.getItemCount(); i++){
combo.addItem(comboBox.getItemAt(i));
}
}
public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
combo.setSelectedItem(value);
return combo;
}
}
#Override
public TableCellEditor getCellEditor(int row, int column) {
Object value = super.getValueAt(row, column);
if(value != null) {
if(value instanceof JComboBox) {
return new DefaultCellEditor((JComboBox)value);
}
return getDefaultEditor(value.getClass());
}
return super.getCellEditor(row, column);
}
And then, override the toString method from JComboBox.
This page might help you, although it seems you are restricted to having the same combobox in all the cells in a column.
You need to create a subclass of JTable to override the method TableCellEditor getCellEditor(int row, int column).
This enables you to set arbitrary cell editors for any row and column combination. The default way is to set the cell editor for an entire column.
(You can also set individual cell renderers by overriding getCellRenderer.)
The easiest way is to implement your own TableModel
public class MyModel extends AbstractTableModel {
List rows;
public int getRowCount() {
return rows.size();
}
public int getColumnCount() {
return 4;
}
public Object getValueAt(int row, int column) {
return rows.get(row).getCol(col); //assuming your row "Object" has a getCol()
}
public Class<?> getColumnClass(int col) {
return Boolean.class;
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
rows.get(rowIndex).getCol(columnIndex).setValue(aValue);
}
}
Load this into you JTable. If you haven't replaced the default cell renderer for Boolean's, all you cells will be rendered as check boxes thanks to you implementation of getColumnClass(). All user input to these check boxes is collected with our setValueAt().