deleting data in java application but it is still displayed in jtable - java

i have written a java application with tables and functions like add,delete or update.
My problem is, that I delete a row in the table and it is deleted in the database, but when I click on a free space of my JTable the deleted row appears again?
here my code:
DAO CLASS
#Override
public void delete(int id) throws SQLException {
handle = new DatabaseHandler();
con = handle.buildConnectionToServer();
query = "DELETE FROM Team WHERE TID="+id;
std = con.createStatement();
std.execute(query);
con.commit();
handle.closeConnection();
}
CONTROLLER
//ActionListener "Delete" Button in "DeleteEquipment"
public void controllActionListenerDeleteEquipmentSubmit(){
main.setActionListenerDeleteEquipmentSubmit(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==main.getDeleteEquipment()){
EquipmentDAO equipment = new EquipmentDAO ();
int a = (int)main.getDeleteEquipmentPanel().getDeleteValues().getValueAt(main.getDeleteValues().getSelectedRow(),0);
try {
equipment.delete(a);
JOptionPane.showMessageDialog(null, "Successfully Deleted");
equipmentArr = equipment.show();
main.getDeleteEquipmentPanel().showAllDelete(equipmentArr);
equipmentArr=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
}
MAINFRAME
//Back Button of "DeleteEquipment" to "ManageEquipment"
public void setActionListenerBackDeleteEquipment(ActionListener actionListener) {
deleteEquipment.getDeleteEquipmentBack().addActionListener(actionListener);
}
public JButton getDeleteEquipmentBack(){
return deleteEquipment.getDeleteEquipmentBack();
}
//Delete Button in DeleteEquipment
public void setActionListenerDeleteEquipmentSubmit(ActionListener actionListener) {
deleteEquipment.getDeleteEquipment().addActionListener(actionListener);
}
public JButton getDeleteEquipment(){
return deleteEquipment.getDeleteEquipment();
}

Related

Why is this event doing as much as the overall clicks?

I have two events that support the button and table by click mouse
if i click te button should remove the record from the list and table. It
happens but program display this exception ArrayIndexOutOfBoundsException:
-1
r.getjTable3().addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
System.out.println(e.getClickCount());
r.getjButton2().addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
String nazwa = r.getjTable3().getValueAt(r.getjTable3().getSelectedRow(), 3).toString();
System.out.println(r.getjTable3().getSelectedRow());
((DefaultTableModel)r.getjTable3().getModel()).removeRow(r.getjTable3().getSelectedRow());
for (Wydarzenie lista1 : lista)
{
if(nazwa==lista1.name)
{
lista.remove(lista1);
}
}
}
});
}
});

Java: Attempt to mutate in notification in JComboBox document listener

I need to create a editable JComboBox that show data from SqLite database, that matches to typed text in JComboBox. I Used DocumentListener and it worked but I got an Exception like below:
Attempt to mutate in notification
This is my code,
org.jdesktop.swingx.autocomplete.AutoCompleteDecorator.decorate(jComboBox1);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final JTextComponent tcA = (JTextComponent) jComboBox1.getEditor().getEditorComponent();
tcA.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void insertUpdate(DocumentEvent e) {
try {
SQDB s = new SQDB();
ResultSet rs = s.getData("SELECT e_word FROM words WHERE e_word LIKE '" + tcA.getText()+ "%'");
while (rs.next()) {
jComboBox1.addItem(rs.getString("e_word"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
}
});
How to solve this Exception. Thank you

enable a jcombobox without pressing enter

I am working in java swing in netbeans.
I have a textfield. I would like that a combobox will be enabled only if the text written in the textfield is greatter tahn one.
My code works if I press the enter key. But I would like to make it work just by writting in the textfield. How can I do this?
private void nmrintervTXTActionPerformed(java.awt.event.ActionEvent evt) {
String text = this.nmrintervTXT.getText();
System.out.println(text);
if (!text.isEmpty()) {
if (Integer.parseInt(text) > 1) {
this.evidenceOtherApplicantsTXT.setEnabled(true);
}
}
}
See addCaretListener API.
textfield.addCaretListener(new CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
System.out.println("caretUpdate with new text: "+textfield.getText());
}
});
class MyDocumentListener implements DocumentListener {
#Override
public void insertUpdate(javax.swing.event.DocumentEvent e) {
update(e);
}
#Override
public void removeUpdate(javax.swing.event.DocumentEvent e) {
update(e);
}
#Override
public void changedUpdate(javax.swing.event.DocumentEvent e) {
}
public void update(javax.swing.event.DocumentEvent e) {
String text = nmrintervTXT.getText();
try {
evidenceOtherApplicantsTXT.setEnabled(Integer.parseInt(text) > 1);
} catch (NumberFormatException nfe) {
evidenceOtherApplicantsTXT.setEnabled(false);
}
}
}
public MyClass() {
initComponents();
}
#SuppressWarnings("unchecked")
nmrintervTXT = new javax.swing.JTextField();
nmrintervTXT.getDocument().addDocumentListener(new MyDocumentListener());
I think the parameter e was in fault in update in MyDocumentListener.

Enable Jbutton only if Validation is True

What is the best way to validate swing application's input fields such as text fields, comboboxes, etc and let the user to press Save button only if everything is ok. Assume that Search function also in the same interface. So searching for record will also fill up input fields. But Save button should remain disable in that case.
initComponents();
btnSave.setEnabled(false);
txt1.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void changedUpdate(DocumentEvent e) {
}
#Override
public void removeUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
#Override
public void insertUpdate(DocumentEvent e) {
validate(txt1.getText(),e);
}
public void validate(String enteredText,DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
}
if(enteredText.equals(currText)){
//if validated successfully
btnSave.setEnabled(false);
}else{
btnSave.setEnabled(true);
}
}
});
did you try like this?
final JTextField textField = new JTextField();
final JButton submitBtn = new JButton();
submitBtn.setEnabled(true);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
validate(e);
}
public void removeUpdate(DocumentEvent e) {
validate(e);
}
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(String enteredText) {
String currText = "";
try {
Document doc = (Document)e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
//validation of currText here
//if validated successfully
submitBtn.setEnabled(true);
//else
submitBtn.setEnabled(false);
}
});
Condition the enabled property of your Save button using setEnabled() in two places:
In your implementation of shouldYieldFocus() in an InputVerifier attached to each relevant component. The tutorial and some examples are cited here.
In your component's normal listener.
Create a method to check if all the inputs are completed or/and all the validations are passed and finally return a boolean.
public boolean validate(...){
//some stuff
if(validated){
return true;
}else{
return false;
}
}
then you can use it like.
button.setEnabled(validate(...));

Column moved [finished] event in JTable

How should I detect that column moved action is finished in JTable? I've added columnModeListener to my column model but the problem is columnMoved method is called every time a column moves (by certain pixels). I don't want this behavior. I just want to detect when the column dragging is finished.
columnModel.addColumnModelListener(new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
}
public void columnRemoved(TableColumnModelEvent e) {
}
public void columnMoved(TableColumnModelEvent e) {
//this is called so many times
//I don't want this, but something like column moved finished event
System.out.println("Moved "+e.getFromIndex()+", "+e.getToIndex());
}
public void columnMarginChanged(ChangeEvent e) {
}
public void columnSelectionChanged(ListSelectionEvent e) {
}
});
I hope it is clear what I'm looking for. Thanks.
This is what I ended up doing. I know it is dirty, but it fits for what I'm looking:
boolean dragComplete = false;
apTable.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
if (dragComplete) {
System.out.println("Drag completed");
}
dragComplete = false;
}
});
columnModel.addColumnModelListener(new TableColumnModelListener() {
public void columnAdded(TableColumnModelEvent e) {
}
public void columnRemoved(TableColumnModelEvent e) {
}
public void columnMoved(TableColumnModelEvent e) {
dragComplete = true;
}
public void columnMarginChanged(ChangeEvent e) {
}
public void columnSelectionChanged(ListSelectionEvent e) {
}
});
Here's an inner class I use to determine when the column ordering has changed. Note that the user may not have let go of the mouse at this point, so the dragging may continue further.
private class ColumnUpdateListener implements TableColumnModelListener {
int lastFrom = 0;
int lastTo = 0;
private void verifyChange(int from, int to) {
if (from != lastFrom || to != lastTo) {
lastFrom = from;
lastTo = to;
///////////////////////////////////////
// Column order has changed! Do something here
///////////////////////////////////////
}
}
public void columnMoved(TableColumnModelEvent e) {
verifyChange(e.getFromIndex(), e.getToIndex());
}
public void columnAdded(TableColumnModelEvent e) {
verifyChange(e.getFromIndex(), e.getToIndex());
}
public void columnRemoved(TableColumnModelEvent e) {
verifyChange(e.getFromIndex(), e.getToIndex());
}
public void columnMarginChanged(ChangeEvent e) {}
public void columnSelectionChanged(ListSelectionEvent e) {}
}
It's worked well for me.
This might be a better approach:
table.setTableHeader(new JTableHeader(table.getColumnModel()) {
#Override
public void setDraggedColumn(TableColumn column) {
boolean finished = draggedColumn != null && column == null;
super.setDraggedColumn(column);
if (finished) {
onColumnChange(table); // Handle the event here...
}
}
});
This is what works for me (both column movements and margin resizes):
I extend the table and override the columnMoved and columnMarginChanged
methods in the following way:
... first add some variables for state keeping
private int lastMovementDistance = 0;
private boolean bigMove = false;
private boolean resizeBegan = false;
...
#Override
public void columnMarginChanged(ChangeEvent e) {
super.columnMarginChanged(e);
if (isShowing()){
resizeBegan = true;
}
}
#Override
public void columnMoved(TableColumnModelEvent e) {
super.columnMoved(e);
//this will be set to 0 when the column is dragged
//to where it should begin if released
lastMovementDistance = Math.abs(getTableHeader().getDraggedDistance());
if (e.getFromIndex() != e.getToIndex()){
//note, this does not guarantee that the columns will be eventually
//swapped - the user may move the column back.
//but it prevents us from reacting to movements where
//the user hasn't even moved the column further then its nearby region.
//Works for me, because I don't care if the columns stay the same
//I only need the updates to be infrequent and don't want to miss
//changes to the column order
bigMove = true;
}
}
... then in the constructor of my table i do this:
public MyTable(){
...
getTableHeader().addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent evt) {
if (bigMove && lastMovementDistance == 0 ){
//react! the tables have possibly switched!
}
else if (resizeBegan){
//react! columns resized
}
resizeBegan = false;
bigMove = false;
}
});
...
}
It is kinda like a hack, but it works for me.
Nice answer on your own question ashokgelal. Just a little improvement I think. Your code also trigger on single click on the header. Using one more flag you can prevent the 'dragComplete' trigger when the column haven't really changed.
Modified code:
boolean mDraggingColumn = false;
boolean mColumnCHangedIndex = false;
tblObjects.getTableHeader().addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
if (mDraggingColumn && mColumnCHangedIndex) {
System.out.println("Column changed");
}
mDraggingColumn = false;
mColumnCHangedIndex = false;
}
});
tblObjects.getColumnModel().addColumnModelListener(new TableColumnModelListener() {
#Override
public void columnAdded(TableColumnModelEvent e) {}
#Override
public void columnRemoved(TableColumnModelEvent e) {}
#Override
public void columnMoved(TableColumnModelEvent e) {
mDraggingColumn = true;
if (e.getFromIndex() != e.getToIndex()) {
mColumnCHangedIndex = true;
}
}
#Override
public void columnMarginChanged(ChangeEvent e) {}
#Override
public void columnSelectionChanged(ListSelectionEvent e) {}
});
If I understand you correctly, maybe you want to look at the mouse listeners. Maybe the MOUSE_RELEASED event?
All answers fail at one use-case: if the table is in a layout filling up the entire window, then resizing the window will resize the table and thus its columns. By watching for mouse events on the column headers, we fail to receive the event when the user resize the window.
I looked at the JTable&friends source-code, and the columnMarginChanged() method is always called in a sub-sub-sub...-function called by JTable.doLayout().
Then, my solution is to watch for doLayout() calls that trigger at least one columnMarginChanged().
In fact, columnMarginChanged() is called for every columns.
Here is my solution:
private class ResizableJTable extends JTable {
private TableColumnModelListener columnModelListener;
private boolean columnsWereResized;
#Override
public void setColumnModel(TableColumnModel columnModel) {
if (getColumnModel() != null) {
getColumnModel().removeColumnModelListener(columnModelListener);
columnModelListener = null;
}
if (columnModel != null) {
columnModelListener = new TableColumnModelListener() {
public void columnSelectionChanged(ListSelectionEvent e) {
// Nothing to do
}
public void columnRemoved(TableColumnModelEvent e) {
// Nothing to do
}
public void columnMoved(TableColumnModelEvent e) {
// Nothing to do
}
public void columnMarginChanged(ChangeEvent e) {
columnsWereResized = true;
}
public void columnAdded(TableColumnModelEvent e) {
// Nothing to do
}
};
columnModel.addColumnModelListener(columnModelListener);
}
super.setColumnModel(columnModel);
}
#Override
public void doLayout() {
columnsWereResized = false;
super.doLayout();
if (columnsWereResized) {
onColumnsResized();
}
}
/**
* Sub-classes can override this method to
* get the columns-were-resized event.
* By default this method must be empty,
* but here we added debug code.
*/
protected void onColumnsResized() {
int[] columnSizes = getColumnSizes();
String sizes = "";
for (int i : columnSizes) {
sizes += i + " ";
}
System.out.println("COLUMNS RESIZED: [ " + sizes + "]");
}
protected int[] getColumnSizes() {
TableColumnModel columnModel = getTableHeader().getColumnModel();
int columnCount = columnModel.getColumnCount();
int[] columnSizes = new int[columnCount];
for(int i = 0; i < columnCount; i++) {
TableColumn column = columnModel.getColumn(i);
columnSizes[i] = column.getWidth();
}
return columnSizes;
}
}

Categories