Empty item selected from editable autocomplete Jcombobox - java

I have a problem with jcombobox when i try to select an item from autocomplete JcomboBox , this is the Jcombobox i created and filled from sqlite database with actionListener :
So what i try to do is to write the first lettre and it will be completed automatically and than with jComboBox1ActionPerformed(evt); i will get linked data from sqlite database and add it to Label
jXLabel2.setText(con.getData()[0][0]);
jXTextField1.setText(con.getData()[0][1]);
when i write a first letter of an item it give me this error
Opened database successfully
Records created successfully
SELECT COUNT(*) As COUNTR FROM Articles WHERE Designation = ''
0
SELECT * FROM Articles WHERE Designation = ''
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at gestionstocktaza.ModArticles.jComboBox2ActionPerformed(ModArticles.java:222)
but if i didn't use con.getData()[0][0]) or con.getData()[0][1]) it didn't return any error
and data will be selected normally , also when u use these two in a 'FOR Statemet' it work fine
for(int i=0;i<da.length;i++){
jXLabel2.setText(da[i][0]);
jXTextField1.setText(da[i][1]);
}
i don't know what is the problem with method return a two dimensional table of string getData

You have closed the connection before addActionListener to your ComboBox
con.CloseDB();
jComboBox2.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
jComboBox2ActionPerformed(evt);
}
});

Related

Return type of method which fill comboBox

I'm working on a simple GUI where I drag combobox and edit the values here I i have a class categories and then 3 methods of rice,sweets and meal. I would like to be to call these three methods on my frame and then from there I want to fill the values into the combo box. An important thing that these 3 methods of categories class are connected with access so they fetch data from there. My question is: What will be the return type of these particular methods?
public String rice()
{
String query ="select * from categories";
String end=null;
String a ;
try{
ps=conn.prepareStatement(query);
rs=ps.executeQuery();
while(rs.next())
{
end=end+rs.getString("Rice")+"\t";
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
return end;
}`
now in another class
Combo_boxes obj = new Combo_boxes();
comboBox.addItem(obj.rice());
When I call this method it will to return a value of 1 row of database and then I want to place it into the combo box and then next row so from this,i will place every item from database. When I update my database it should automatically update the combo box.

Populate combobox of table cell with different value based on selection of table row in java

I want to populate the combo box with the value from database based on the selection of table row, it works, but only when I select the different cell of the row then select required combo box cell. But if I select the combobox cell of another row, it shows previous items, and after selecting one of them, if I again click on the combobox it will populate with fresh values. I want the fresh values be populated when I click on row or even combo box cell. Please help.
The code is given below:-
String columnName[] = { "Date","Voucher ID","Voucher No","Amount","VOUCHER_NARRATION","Exp. Head" };
String dataValues[][] = {};
voucherTable=new JTable(dataValues,columnName);
voucherTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel list=voucherTable.getSelectionModel();
voucherTable.setSelectionModel(list);
list.addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent lt) {
try {
voucherid=voucherTable.getValueAt(voucherTable.getSelectedRow(),1).toString();
System.out.println(voucherid);
comboBox.removeAllItems();
TableColumn road=voucherTable.getColumnModel().getColumn(5);
voucherTable.getColumnModel().getColumn(5).setCellEditor(new DefaultCellEditor(new VoucherUpdate().getExpHead(voucherid)));
} catch(Exception h) {
System.err.println(h);
return;
}
}
});
public JComboBox getExpHead(String vid) {
String voucherId=vid;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:SARALIFMS","SARALIFMS","O391120SUMAN");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("SELECT E.EXP_ID,EXP_HEAD FROM TD_VOUCHER_SUMAN D, MM_PRIA_EXPENDITURE E"
+" WHERE VOUCHER_ID='"+voucherId+"' AND D.ACCOUNT_CODE=E.ACCOUNT_CODE");
while(rs.next()) {
String expHead=rs.getString("EXP_HEAD");
comboBox.addItem(expHead);
}
conn.close();
} catch(Exception e) {
System.out.println(e);
}
return comboBox;
}
it works, but only when I select the different cell of the row then select required combo box cell
When you click on a cell using a combo box as an editor, the editor is invoked BEFORE the selected row has been updated. So this is a timing issue.
One solution is to override the getCellEditor(...) method of the JTable to load the data when the editor is actually invoked. At this point in time the selected row will be updated and you can get the data for the appropriate row.
This approach is demonstrated in this question: https://stackoverflow.com/a/4211552/131872
Note you may want to consider caching the data so you don't do an SQL access every time you edit the cell.

Java DefaultTableModel- how do I remove the selected row?

I have a table displayed in my Java GUI, which the user can add rows to by clicking an 'Add' button. The cells in the row that is added to the table are all editable by default, and the user can select each row/ cell as they wish.
I now want to add the functionality to remove a row from the table, but I can't seem to find the correct way to do this with a DefaultTableModel data type.
I have added the following code to the action listener for my 'remove row' button:
removeBtn.addActionListener(new ActionListener(){
public void removeRow(){
DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
model.removeRow();
}
});
However, the removeRow() method requires a parameter of type int (the index number of the row I want to remove). How can I get the 'selected row' from the DefaultTableModel? There doesn't appear to be a method that allows you to do this...
You can obtain the index from the table.
removeBtn.addActionListener(new ActionListener(){
public void removeRow(){
int selRow = jEntityFilterTable.getSelectedRow();
if(selRow != -1) {
DefaultTableModel model = (DefaultTableModel)jEntityFilterTable.getModel();
model.removeRow(selRow);
}
}
});

What is the best way to listen for changes in JTable cell values and update database accordingly?

I'm building and app with multiple JTables and I need to detect when cell value change occurs so I can update it in the database. I tried TableModelListener and overriding tableChanged, but it fires only when I click away (click on another row) after I have edited a cell.
Any other way to do this?
You can implement the CellEditorListener interface, as shown in this example. Note that JTable itself is a CellEditorListener.
It may also be convenient to terminate the edit when focus is lost, as shown here:
table.putClientProperty("terminateEditOnFocusLost", true);
More Swing client properties may be found here.
I'm agreeing with #mKorbel - unless all your input is checkboxes and dropdowns, you're going to want to wait until the cell editing is stopped (you don't want to commit to the database every time a letter is typed in a textbox).
If the problem is that it's not committing after focus has gone to another component, add a FocusListener that stops editing the table when focus is lost on the table:
Example:
final JTable table = new JTable();
table.addFocusListener(new FocusAdapter() {
#Override
public void focusLost(FocusEvent e) {
TableCellEditor tce = table.getCellEditor();
if(tce != null)
tce.stopCellEditing();
}
});
I use the enter key so everytime a user hit enter the cell will update.
DefaultTableModel dtm = new DefaultTableModel(data, columnNames);
JTable table = new JTable(dtm);
table.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
int row = table.getSelectedRow();
int column = table.getSelectedColumn();
// resul is the new value to insert in the DB
String resul = table.getValueAt(row, column).toString();
// id is the primary key of my DB
String id = table.getValueAt(row, 0).toString();
// update is my method to update. Update needs the id for
// the where clausule. resul is the value that will receive
// the cell and you need column to tell what to update.
update(id, resul, column);
}
}
});
This is also handy if you want to stop the editing on an event handler from selection change or save button.
if (table.isEditing())
table.getCellEditor().stopCellEditing();

Get TableCell content for SQL query

I'm writing an SQL CRUD application and stuck on the delete button problem. I have a table with 4 columns and a delete button in the fifth. To make an SQL query I need to get info from these 4 columns. I can get a row number and a column name, how to get cell content on row/column intersection?
Assuming the fifth column has a custom cell factory that puts the delete button in its custom TableCell, this delete button can own an action like:
btnDelete.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
param.getTableView().getSelectionModel().select(getIndex());
Person item = personTable.getSelectionModel().getSelectedItem();
if (item != null) {
// Logic of deleting current record here
System.out.println(item.getName());
}
}
});
The full sscce, Putting button into the table column more elegantly.

Categories