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.
Related
I want to update a swing table's row value in the DB, clear the model, and load the new model with the new updated value. The problem is that when I click the button to update the value, the model is cleared but no data is shown in the table. What am I doing wrong?
Parts of the code not relative to the table have been removed in order to make the example easier.
public class ShowValues extends JFrame {
//Attributes
private DefaultTableModel model;
private JTable table = new JTable()
{
public boolean isCellEditable(int row, int column)
{
return false;
};
};
public ShowValues() {
btnDeleteItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
int selectedRowNumber = table.getSelectedRow();
String selectedItemId = (String) table.getModel().getValueAt(selectedRowNumber, 0);
//code to change selected item's state to deleted in the DB
model.setRowCount(0); //clear model
showTable(); //load new model
labelMsg.setText("Item deleted");
}
});
btnDeleteItem.setBounds(200, 320, 203, 57);
contentPane.add(btnDeleteItem);
}
public void showTable()
{
String columnNames[] = {"Item Id", "Item Name", "Item price"};
//code to get the data form the DB
String dataValues[][] = new String[itemNum][3];
for(int i=0; i<itemNum; i++)
{
dataValues[i][0] = idItem[i];
dataValues[i][1] = nameItem[i];
dataValues[i][2] = priceItem[i];
}
model = new DefaultTableModel(dataValues, columnNames);
table.setModel(model);
scrollPane = new JScrollPane(table);
scrollPane.setBounds(17, 20, 490, 205);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
topPanel.add(scrollPane);
}
}
//code to change selected item's state to deleted in the DB
Why would you want to reload all the data just because the change the value of one property in the row? That is not very efficient.
Just use the setValueAt(...) method to change the value in the JTable.
The problem is that when I click the button to update the value, the model is cleared but no data is shown in the table
The problem is you create a new JTable, but you never add the table to the viewport of your JScrollPane.
The solution is to NOT create a new JTable. Just create a new TableModel. Then you can just use:
table.setModel( theNewlyCreateTableModel );
In my first column in jtable I have set the setCellEditor (new DefaultCellEditor(comboBox).
All I want is when I open the the table, I find the first cell which has the editable Combobox with the cursor blinking ready for input.
Here's the code of what I have done what I have done.
try {
//Already registered so open mainWindow
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
final mainWindow mainn = new mainWindow();
//get the institution name and display it as the title
String companyName = dbutils.checker.getCompanyName();
//disable all items on system
disable();
mainn.setTitle("[" + companyName + "]");
mainn.setExtendedState(Frame.MAXIMIZED_BOTH);
TableColumn items = mainWindow.salesTable.getColumnModel().getColumn(0);
final JComboBox comboBox = new JComboBox();
comboBox.addItem("250AZ0002C20140725");
comboBox.addItem("250AZ0001C20140725");
comboBox.addItem("250AZ0003C20140725");
comboBox.addItem("250AZ0004C20140725");
comboBox.setEditable(true);
items.setCellEditor(new DefaultCellEditor(comboBox));
ComboBoxEditor editor = comboBox.getEditor();
JTextField textField = (JTextField)editor.getEditorComponent();
textField.setCaretPosition(0);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
mainWindow.salesTable.requestFocus();
comboBox.requestFocus();
mainWindow.salesTable.changeSelection(0, 0, false, false);
mainWindow.salesTable.editCellAt(0, 0);
}
});
readBarcode();
mainn.setVisible(true);
} catch (Exception ex) {....}
Its pretty simple, JTable always has focus by default. To surrender the focus to the cells there is a method Jtable.setSurrendersFocusOnKeystroke(true).
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;
}
}
}
Currently in a Jtable there is a space for a name and then a combobox in each column header. When the header name is clicked I would like the default sorting to still take place but when the combobox is clicked I would like it to not sort.
I've tried consuming the mouseclick event when the combobox is clicked but the AWT event handlers have already received the event before my listener.
TableRowSorter is declared as such:
TableRowSorter<TableModel> tableRowSorter = (TableRowSorter<TableModel>) mainTable.getRowSorter();
tableRowSorter.addRowSorterListener(new RowSorterListener() {
#Override
public void sorterChanged(RowSorterEvent e) {
if (!(mainTable.getSelectedRow() < 0)) {
Rectangle r = mainTable.getCellRect(mainTable.getSelectedRow(), 0, true);
Point p = mainScrollPane.getViewport().getViewPosition();
r.setLocation(r.x, r.y - p.y);
mainScrollPane.getViewport().scrollRectToVisible(r);
}
}
});
//Section for popupmenu located in jtable class
aggregationMenu = new JPopupMenu();
aggregationMenu.setInvoker(this);
for (AggregationType type : AggregationType.values()) {
if (type == AggregationType.GROUP)
continue;
JMenuItem mi = new JMenuItem();
mi.setText(type.toString());
mi.addActionListener(this);
aggregationMenu.add(mi);
}
Can someone help me with this listener?
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent e){
if(e.getValueIsAdjusting()){
ListSelectionModel model = table.getSelectionModel();
int lead = model.getLeadSelectionIndex();
displayRowValues(lead);
}
}
private void displayRowValues(int rowIndex){
String country = "";
Object oCountry = table.getValueAt(rowIndex, 0);
country += oCountry.toString();
countryTxt.setText(country );
}
});
It's supposed to send data from cell in jtable (table) into a textfield (countryTxt) when one of the row's is selected, but it works only when I click on row and not when I'm cycling trough my table with arrow key's.
The problem is with this line:
if (e.getValueIsAdjusting()) {
Replace this with:
if (e.getValueIsAdjusting()) return;
This is a check for multiple selection events BTW.
If you comment out e.getValueIsAdjusting() it works.
http://docs.oracle.com/javase/6/docs/api/javax/swing/ListSelectionModel.html#setValueIsAdjusting(boolean)