2

I have a JButton that updates data in my MYSQL database, how do i enable the JButton only when there are changes detected in my JTextFields?

...this is my code for the update button

private void updateBtnActionPerformed(java.awt.event.ActionEvent evt) {  

try{    

            String a = IDField.getText();            

            String query = "UPDATE employee SET First_Name=?, Last_Name=?,Job_Title=? WHERE ID=?"; 
            PreparedStatement ps = conn.prepareStatement(query);


            ps.setString(1, FNameField.getText());
            ps.setString(2, LNameField.getText());
            ps.setString(3, jobTitleField.getText());
            ps.setString(4, a);

            ps.executeUpdate();

            JOptionPane.showMessageDialog(null, "Successfully Updated Employee Record!");

            }catch(Exception e){
            System.out.println(e);
        }
Srijani Ghosh
  • 3,935
  • 7
  • 37
  • 68
JustineP
  • 63
  • 1
  • 1
  • 9

2 Answers2

1

public static void addChangeListener(JTextComponent text, ChangeListener changeListener) { Objects.requireNonNull(text); Objects.requireNonNull(changeListener); DocumentListener dl = new DocumentListener() { private int lastChange = 0, lastNotifiedChange = 0;

    @Override
    public void insertUpdate(DocumentEvent e) {
        changedUpdate(e);
    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        changedUpdate(e);
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        lastChange++;
        SwingUtilities.invokeLater(() -> {
            if (lastNotifiedChange != lastChange) {
                lastNotifiedChange = lastChange;
                changeListener.stateChanged(new ChangeEvent(text));
            }
        });
    }
};
text.addPropertyChangeListener("document", (PropertyChangeEvent e) -> {
    Document d1 = (Document)e.getOldValue();
    Document d2 = (Document)e.getNewValue();
    if (d1 != null) d1.removeDocumentListener(dl);
    if (d2 != null) d2.addDocumentListener(dl);
    dl.changedUpdate(null);
});
Document d = text.getDocument();
if (d != null) d.addDocumentListener(dl);

}

How do i implement this?? addChangeListener(someTextBox, e -> doSomething()); So that when change is Detected in the JTextField, my Update Button will notify about the changes made and if no changes were made, UpdateBtn will not update anything..

Any further help??

JustineP
  • 63
  • 1
  • 1
  • 9
0

You can add the valueChangeListener on the JTextField.

Please visit this Stack overflow link for more - Value Change Listener to JTextField

Community
  • 1
  • 1
Srijani Ghosh
  • 3,935
  • 7
  • 37
  • 68