can i add the combobox into particular cell of the JTable? - java

I want to add combobox into a cell of JTable.
model=new DefaultTableModel(data,col);
JTableHeader head=new JTableHeader();
head.setBackground(Color.BLUE);
table=new JTable(model);
table.add(head);
JComboBox combo = new JComboBox();
combo.addItem("Names");
combo.addItem("Antony");
combo.addItem("Victor");
combo.addItem("Ramkumar");
table.add(combo);
But i cant get the combobox in the cell. Is it possible to set combo box?

You need to set the TableCellEditor of the JTable. It's better to search the Java Tutorials, but here is a short explain.
JTable uses three main classes to work:
1) TableModel: it's function is to say how many rows and columns the table has and to serve the data of the Table, it's main methods are getValue(row,col) and setValue(value, row,col). And fire events to notify the JTable repaints.
2) TableCellRenderer: it's main purpose it's to draw components in the JTable's cells. This components are only painted: NOT WORK! if you draw a JComboBox it won't desplegate if you click on it or if you draw a JCheckbox it wont't select/unselect.
3) TableCellEditor: it's main purpose it's to draw a component within a JTableCell to edit the value of the cell. It receives events and decide when to start the editing, then it's getTableCellEditorComponent method is called to return the editor component. The component returned has to launch events so that the TableCellEditor knows when to stop the editing and get the value and use it to call the TableModel.setvalue... or cancel the editing.
So that to show JComboBox in a JTable you must create your own TableCellEditor, not an easy task if you haven't done it before.

Take alook at this
Java tutorial and search in this page for "Using a Combo Box as an Editor"

Try this: its working for me..click on the cell to see the combobox.
private void comboloader() {
try {
TableColumn gradeColumn = jTable1.getColumnModel().getColumn(0);
JComboBox comboBox = new JComboBox();
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));
} catch (Exception e) {
}
}

Related

Listen for selection on already selected cell for JTable

Is there any way to listener for cell selection even on already selected cells with a JTable, other than using a MouseListener?
I have a JTable with a row and column listener. Neither listener fires when selecting an already selected cell:
JTable table() {
JTable table = new JTable(10, 10);
table.getSelectionModel().addListSelectionListener(rowListener);
table.getColumnModel().getSelectionModel().addListSelectionListener(colListener);
return table;
}
ListSelectionListener rowListener = event -> {
if(event.getValueIsAdjusting())
return;
System.out.println("Row: "+((ListSelectionModel) event.getSource()).getMinSelectionIndex());
};
ListSelectionListener colListener = event -> {
if(event.getValueIsAdjusting())
return;
System.out.println("Col: "+((ListSelectionModel) event.getSource()).getMinSelectionIndex());
};
My goal was to switch cells on/off. It works, other than the fact that the listeners do not fire when selecting an already selected cell, which is represented through the SSCCE above.
There doesn't seem to be any listener I can attach to the JTable (or it's models/selection models) to handle this, unless I were to use a MouseListener and manually manage the cooridnates. Using a TableModelListener, I can listen for changes, but this event is targeted at a previous cell (that has been deselected), and clicking an area that doesn't select a cell would cause that listener to fire.
My goal was to switch cells on/off.
Store Boolean data in the TableModel. Then whenever you click on the cell the value will toggle between true/false.
The default renderer for a Boolean value is a check box. You can always use a custom renderer if you don't want to see the check box.

Repaint Table issue with Swing JTable

I am working with swing JTable and have a trouble with repainting table. I draw a JTable with thr following code
Object[] column = new Object[]{"Entity", "Attribute"};
Object[][] rowData = new Object[][]{{"E1", "A1"},{"E2", "A2"}};
TableCellRenderer cellRenderer = new TableCellRenderer();
JTable table = new JTable(new DefaultTableModel(rowData, column));
table.setCellSelectionEnabled(true);
table.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);
Below is my table renderer code ..
public class TableCellRenderer implements javax.swing.table.TableCellRenderer {
//private JPanel panel;
JTextField field;
private JTable table;
#Override
public Component getTableCellRendererComponent(final JTable table, final Object value,
boolean isSelected, boolean hasFocus, final int row, final int column) {
this.table = table;
//JTextField field = null;
System.out.println("Rendere : Row : " + row + "Column : " + column);
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JButton button = new JButton("?");
button.setPreferredSize(new Dimension(20, panel.getHeight()));
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new SelectionDialog(panel, table, value, row, column);
}
});
if(table.getValueAt(row, column) != null){
field = new JTextField(table.getValueAt(row, column).toString());
}else{
field = new JTextField(table.getValueAt(row, column).toString());
}
field.setPreferredSize(new Dimension(30, panel.getHeight()));
panel.add(field, BorderLayout.WEST);
panel.add(button, BorderLayout.EAST);
return panel;
}
this is how i am updating contents of a cell in table..
SelectionDialog.this.table.getModel().setValueAt("E7", 0, 0);
I am updating the table model data via the SelectionDialog for e.g change data at row 0, colum 0 to E7 etc. After changing data in table model i have tried the following options but none of them has refreshed the table data in view however the data in model of JTable was updated correctly. If I add a new row on the fly and then call the below methods then every thing work fine but if I modify data in the model of an existing row then none of the solution mentioned below is working
//((DefaultTableModel)SelectionDialog.this.table.getModel()).addRow(new Object[]{"E3", "A3"});
//((DefaultTableModel)SelectionDialog.this.table.getModel()).fireTableCellUpdated(SelectionDialog.this.row, SelectionDialog.this.column);
//((DefaultTableModel)SelectionDialog.this.table.getModel()).fireTableChanged(new TableModelEvent(SelectionDialog.this.table.getModel()));
//((DefaultTableModel)SelectionDialog.this.table.getModel()).fireTableStructureChanged();
//SelectionDialog.this.table.repaint();
// SelectionDialog.this.table.revalidate();
Please provide any insights about the problem as I am to swing and may have missed some very prominent things.
Edit 1: Just adding one more note which i wanted to place earlier but don't know how i missed. Table is not updated in general but if i focus out from the cell in which change was made or i change the size of table then it immediately change the contents of that particular cell to fresh selected value.
Problem Solved:
I am placing my findings for someone who is facing similar problem.
I rendered a button and a text box inside each cell in my table. When button was clicked (Editor code is not provided as it looks irrelevant to me to place here) a dialog appear which inputs value from user and update the specific column and row.
The lines i mentioned as not working at the end of my post (before edit 1) were working correctly however renderer was not executing unless i manually focus out from the selected cell (whose button was clicked) or manually change the size of jtable which make sense as button was inside editor and button click shows that cell is edited and off-course renderer will not execute unless editing is finished which requires focus out or enter key etc.
I applied the following code as
table.editCellAt(-1, -1);
It focus out from the edited cell (edited with the button) and hence renderer executes and work as expected.
When you are using a DefaultTableModel and you want to update a certain value, you need to use the DefaultTableModel#setValueAt method.
Calling this method (on the Event Dispatch Thread of course) will update your model and fire the necessary events. Those events will cause your JTable to update itself.
A few additional remarks about your renderer:
Creating new components in each call of your renderer is not the way to go. This becomes incredibly slow for large tables. Create all components once in the constructor of your renderer, and just update their state
Adding a JButton to your table in the renderer has no effect, unless you have an editor as well. The button will not be clickable, and the action listener you attach to it will never be called. See the renderers and editors section in the JTable tutorial for more information.
There should be no need to call getValueAt in your renderer. The value is passed in as one of the arguments

getSelectedRow on a combobox cell editor

I need a listener on a CombobBox which is a cellEditor on a JTable.
This listener must give me the new selected value and the row id.
Problem with my below solution is that the listner is linked to all rows, so when I change one ComboBox value in one row, then move to another row (with a different combo value) an event is raised, but the selected row has not yet changed. How can I get rid of this case ?
Thanks
column = jTableCheck.getColumnModel().getColumn(9);
JComboBox comboBox = new JComboBox(comboGenre);
comboBox.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
int row = jTableCheck.getSelectedRow();
Popup.info(e.getItem() + " SELECTED, row="+row);
}
}
});
column.setCellEditor(new DefaultCellEditor(comboBox));
Don't use an ItemListener on the combo box.
Instead you should be using a TableModelListener. An event will be fired whenever the data in the TableModel is changed. So you add the TableModelListener to the TableModel of your JTable.
The TableModelEvent will give your row/column of the cell that changed. You can get the changed value from the TableModel.
Or maybe you would want to use a Table Cell Listener which is similar to the TableModelListener except the code is only invoked when the value is actually changed and you use an Action to do the processing.
In fact, I already used a TableCellListener on another table, but forgot about that!
I found out a usefull class here: http://tips4java.wordpress.com/2009/06/07/table-cell-listener/

Select next cell JTable

I would like to make a jTable in which when user select an uneditable cell then it should change focus to the next editable cell automatically. Important: the user could select a cell by keyboard (tab or arrow) and by mouse clicking. Is it possible?? How to to it?
This link details Programmatically Making Selections in a JTable Component; you'd have to have mouselisteners/etc chained to work off this.
Table Tabbing shows how you can do it with the keyboard.
I've never tried it but you should be able to use a MouseListener to invoke the same Action when you click on a cell.
Just did a quick test for the MouseListener and it seems to work fine:
JTable table = new JTable(...);
final EditableCellFocusAction action =
new EditableCellFocusAction(table, KeyStroke.getKeyStroke("TAB"));
MouseListener ml = new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
JTable table = (JTable)e.getSource();
int row = table.rowAtPoint(e.getPoint());
int column = table.columnAtPoint(e.getPoint());
if (! table.isCellEditable(row, column))
{
ActionEvent event = new ActionEvent(
table,
ActionEvent.ACTION_PERFORMED,
"");
action.actionPerformed(event);
}
}
};
table.addMouseListener(ml);

How to get some interactivity with a JTable

I Have a JTable where the data model contains information from a sql query. Want to get the added ability to take me to a new jpanel by double-clicking a row in the jtabel.
Thnx
You can add a MouseListener to a JTable and then handle the mouseClicked event.
The following code shows a mouseClicked implementation that finds out what row was double clicked. You can then navigate to a panel using this information.
public void mouseClicked(MouseEvent event)
{
if (event.getClickCount() == 2)
{
JTable source = (JTable)event.getSource();
int rowIndex = source.rowAtPoint(event.getPoint());
// get data from table model using row index
// navigate to panel
}
}

Categories

Resources