I set the renderer to the checkbox on jtable using following code
Object[] ColumnData = {"Sr No","Ward Name","Total voters","Action"};
Object[][] RawData=null;
// in loop
model.insertRow(x, new Object[]{ key,ward_name_var,total_vot_var,new Object[]{o}});
model.setValueAt(o,x,3);
tblWard.setModel(model);
Setchk(tblWard,3,checkbox); // by calling this method which contains following
private void Setchk(JTable jTable1, int i, JCheckBox checkbox)
{
jTable1.getColumnModel().getColumn(i).setCellRenderer((new CWCheckBoxRenderer()));
jTable1.getColumnModel().getColumn(i).setCellEditor(new CheckBoxCellEditor());
}
Blockquote
how can we try it for row to set the checkbox on jtable.
thanks in advance.
If your data is of type Boolean.class, the default render will display a checkbox. To change the checkbox in a particular row, you need a corresponding CellEditor. The default render/editor are used here; custom components are illustrated here.
You can simply override the getCellRenderer method of your JTable to return the desired renderer for a given row. Example:
JTable table = new JTable() {
TableCellRenderer getCellRenderer(int row, int column) {
if (row == checkBoxRow)
return myCheckBoxRenderer;
else
return super.getCellRenderer(row, column);
}
};
Related
I want to create a JTable having the last column with advanced options icon. On clicking this last column in the JTable, I want a new JPanel to pop up allowing user to enter input for required 4 string input fields. This JPanel when dismissed, should return to the original JTable.
I am not sure where to save the data for 4 fields from the new JPanel. As their would be 4 string input fields per JTable row, just displayed in the JPanel.
Can my JTabel cell hold an object saving the data?
UseCase: I have a JTable with 10 columns. It is getting very cluttered so I want to move 5 columns to a new panel which will be launched on clicking an advanced options icon in the original JTable last column.
Sample code on how to associate the data from the JPanel with the row in JTable will be highly appreciated.
In order to show a pop-up when cell is clicked, you need a cell editor class. The main purpose of this class is to provide custom editors for cells, but you can use it to trigger some action when your cell is clicked:
public class InfoCellEditor extends AbstractCellEditor implements TableCellEditor {
#Override
public java.awt.Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
InfoObject info = (InfoObject) value;
editButton = new JButton(new InfoAction(info));
editButton.setText("INFO");
editButton.setEnabled(true);
}
private class InfoAction extends AbstractAction {
InfoObject info;
public InfoAction(InfoObject info) {
super();
this.info = info;
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, info.toString());
stopCellEditing();
}
}
}
Then, extend JTable class and implement getColumnClass and isCellEditable methods:
public class MyTable extends JTable {
public MyTable() {
super();
setDefaultEditor(InfoObject.class, new InfoCellEditor());
}
#Override
public Class getColumnClass(int columnIndex) {
if(columnIndex == 4)
return InfoObject.class;
else
return String.class;
}
#Override
public boolean isCellEditable(int row, int column) {
if(column == 4)
return true;
else
return false;
}
}
Lastly, you should make sure that InfoObject instances are inserted to 5th column. And you can also implement a TableCellRenderer for some custom visual representation of that column.
Object headers = new Object[COLUMN_COUNT];
Object cells[][] = new Object[ROW_COUNT][];
...
cells[0][4] = new InfoObject(data[0]);
cells[1][4] = new InfoObject(data[1]);
table.setModel(new DefaultTableModel(cells, headers));
table.getModel().fireTableDataChanged();
table.setVisible();
I've a JTable and a column contains Boolean object, so its view in the table is a JCheckBox. I would like to change the status of the JCheckBox in order to change the data in my model. I set
#Override
public boolean isCellEditable(int i, int y) {
return true;
}
but it doesn't work. Could anyone help me?
If you look at TableModel, you'll notice the method setValueAt(...). When you click the checkbox in the table, this is where this change will propogate.
I'm working on Reflections and Swings for my project. Using reflections I need to get the information of a particular method, and populate a JTable based on its structure.
The table has the following feature:
Some columns will be named based on the parameter type present in the selected method.
Its the same structre for all the primitive data types(int,float,double,String,long,boolean), only the column names get Changed based on the data type.
The problem I face is when there is a User Defined object inside the method parameter.
In that scenario , I want a JButton instead of empty cell in the row (under that parameter type).
I tried learningTableCellRenderer and CellEditor but nothing helped me because all the tutorials i have seen are based on a Static data(rows and columns). In my case both rows and columns have to be generated dynamically and I need to create the JTable based on my data(dynamically).
I'm trying the following code:
rowData = new Object[1][colData.length];
rowData[0][0] = "";
rowData[0][colData.length - 1] = "";
int i = 1;
for (Class tempClass : paramType) {
if (tempClass.getSimpleName().equals("int")
//Primitives
|| tempClass.getSimpleName().equals("float")
|| tempClass.getSimpleName().equals("long")
|| tempClass.getSimpleName().equals("double")
|| tempClass.getSimpleName().equals("boolean")
|| tempClass.getSimpleName().equals("String")){
rowData[0][i] = "";
}
else{
//User Defined obj
rowData[0][i] = new JButton();
}
i++;
}
But the output i'm getting is something like this:
Kindly help me and provide me a hint or kind of tutorial so that i can proceed with this problem. I'm working on the swings for the first time.
The pictures you posted don't help me since the text to too small for me to read so I'm not sure what you are trying to demonstrate. Make sure the data is readable when you post a question is the data is in fact important to the question.
nothing helped me because all the tutorials i have seen are based on a Static data(rows and columns).
Maybe this example will help. It shows how to dynamically determine the renderer/editor for a cell based on the class of the data in the cell:
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TablePropertyEditor extends JFrame
{
public TablePropertyEditor()
{
String[] columnNames = {"Type", "Value"};
Object[][] data =
{
{"String", "I'm a string"},
{"Date", new Date()},
{"Integer", new Integer(123)},
{"Double", new Double(123.45)},
{"Boolean", Boolean.TRUE}
};
JTable table = new JTable(data, columnNames)
{
private Class editingClass;
public TableCellRenderer getCellRenderer(int row, int column)
{
editingClass = null;
int modelColumn = convertColumnIndexToModel(column);
if (modelColumn == 1)
{
Class rowClass = getModel().getValueAt(row, modelColumn).getClass();
return getDefaultRenderer( rowClass );
}
else
return super.getCellRenderer(row, column);
}
public TableCellEditor getCellEditor(int row, int column)
{
editingClass = null;
int modelColumn = convertColumnIndexToModel(column);
if (modelColumn == 1)
{
editingClass = getModel().getValueAt(row, modelColumn).getClass();
return getDefaultEditor( editingClass );
}
else
return super.getCellEditor(row, column);
}
// This method is also invoked by the editor when the value in the editor
// component is saved in the TableModel. The class was saved when the
// editor was invoked so the proper class can be created.
public Class getColumnClass(int column)
{
return editingClass != null ? editingClass : super.getColumnClass(column);
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public static void main(String[] args)
{
TablePropertyEditor frame = new TablePropertyEditor();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
Edit:
instead to get a Button, what should i keep
There is no default renderer/editor for a button, so you will need to store a custom object and create a custom renderer/editor.
Read the section from the Swing tutorial on Editors and Renderers for more information.
Then you have to tell the table about your custom objects with code like:
table.setDefaultRenderer(CustomObject.class, new CustomRenderer());
table.setDefaultEditor(CustomObject.class, new CustomRenderer());
You might be able to use the Table Button Column as the renderer/editor.
There already exist a jtable, and I need to add a column dynamically, then set table cell renderer for that column, the cell renderer is jlabel with icon. I already finished that.
My question is : Right now I need to sort that column based on different icons used in table cell renderer, so how to do that? Thank you.
There are the related code:
JTable tableļ¼// the table is already existed, I cannot change it
TableColumn column = new TableColumn();
column.setHeaderValue("Icon");
column.setCellRenderer(new IconCellRenderer());
table.addColumn(column);
public class IconCellRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
public IconCellRenderer()
{
super();
}
#Override
public Component getTableCellRendererComponent(JTable pTable, Object pValue,
boolean pIsSelected, boolean pHasFocus, int pRow, int pColumn)
{
JLabel label = new JLabel();
if (checkCondition(..))
{
label.setIcon(iconOne);
}
else
{
label.setIcon(iconTwo));
}
label.setHorizontalAlignment(SwingConstants.CENTER);
return label;
}
}
For that purposes you can use TableRowSorter, and set Comparator to needed column. In that comparator you can compare values of cells and sorting them:
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
sorter.setComparator(0, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
return 0;
}
});
table.setRowSorter(sorter);
table is your JTable , model is model of your table.
read more about sorting in JTable.
I am using a JComboBox as a cell editor for my JTable. When I select one of the values from the drop down list of the ComboBox, setValueAt is not getting called. I know this because I have overridden the function. Based on the value selected in this cell, the value in another cell of the same table is fixed. Also, I need to know which is the actionListener for this event, i.e when I change the value in the ComboBox.
The setValueAt does get called only when the focus is changed to another cell in the table, just clicking outside the table also does not help.
#Override
public void setValueAt(Object o,int row,int col)
{
super.setValueAt(o, row, col);
if(((String)o).matches("1"))
{
super.setValueAt(o, col-1, row+1);
return;
}
if(((String)o).contains("/"))
super.setValueAt(((String)o).substring(2), col-1, row+1);
else
super.setValueAt("1/"+(String)o, col-1, row+1);
}
I just found the way...
I need to add an actionListener to the JComboBox component that I created as a member of the CellEditor class and in the listener function, i need to call stopCellEditing so that the setValueAt gets called...