0

I hava a jFrame that when I press F2 calls a jDialog, in this jDialog, put some information and then when the jButton or Enter is pressed or clicked, I get the information and dispose the jDialog.

However, the jDialog is not closing but getting all the information I request.

Here's the code:

    /**
     * Creates new form DialogCPF
     */
    public DialogCPF(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        jFormattedTextField1.addKeyListener(new Tecla() {
            @Override
            public void keyReleased(KeyEvent e) {
               
            }
        });
    }
 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        
        ConsumirWS2 WS = new ConsumirWS2();
        try {
            WS.Buscar();
        } catch (Exception ex) {
            Logger.getLogger(DialogCPF.class.getName()).log(Level.SEVERE, null, ex);
        }
                jButtonSalvar.setEnabled(true);
                jButtonExcluir.setEnabled(false);
                jButtonINSERIR.setEnabled(false);
                jButtonALTERAR.setEnabled(false);
                jButtonPROCURAR.setEnabled(false);
                jTextFieldAPELIDO.setEnabled(true);
                jTextFieldNOME.setEnabled(true);
                jFormattedTextFieldCPF.setEnabled(true);
                jFormattedTextFieldDATA.setEnabled(true);
                jTextFieldID.setEnabled(false);
                /*DialogCPF dialog = new DialogCPF(new javax.swing.JFrame(), false);
                dialog.dispose();*/

                DialogCPF A = (DialogCPF)evt.getSource();
                A.dispose();
                
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DialogCPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DialogCPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DialogCPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DialogCPF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                DialogCPF dialog = new DialogCPF(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                
                dialog.addKeyListener(new KeyListener(){  

        @Override
        public void keyTyped(KeyEvent e) {
            // Nothing
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // Nothing 
        }

        @Override
        public void keyReleased(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
        ConsumirWS2 WS = new ConsumirWS2();
        try {
            WS.Buscar();
        } catch (Exception ex) {
            Logger.getLogger(DialogCPF.class.getName()).log(Level.SEVERE, null, ex);
        }
                jButtonSalvar.setEnabled(true);
                jButtonExcluir.setEnabled(false);
                jButtonINSERIR.setEnabled(false);
                jButtonALTERAR.setEnabled(false);
                jButtonPROCURAR.setEnabled(false);
                jTextFieldAPELIDO.setEnabled(true);
                jTextFieldNOME.setEnabled(true);
                jFormattedTextFieldCPF.setEnabled(true);
                jFormattedTextFieldDATA.setEnabled(true);
                jTextFieldID.setEnabled(false);
                DialogCPF dialog = new DialogCPF(new javax.swing.JFrame(), true);
                //dialog.setEnabled(false);
                dialog.dispose();
                }
            }
        });        
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    public static javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   
}

I already tried This, this and this solution, however, I could not manage to bring a solution

  • I would strongly recommend taking some time to reading through [How to Write an Action Listener](https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html), in particular with regards to how they relate to [using buttons](https://docs.oracle.com/javase/tutorial/uiswing/components/button.html) and [text fields](https://docs.oracle.com/javase/tutorial/uiswing/components/textfield.html) – MadProgrammer Feb 21 '22 at 20:20
  • 1
    I'd also strongly recommend making use of [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) over `KeyListener`. I'd also recommend providing a [mcve] – MadProgrammer Feb 21 '22 at 20:21

1 Answers1

1

This...

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:

    ConsumirWS2 WS = new ConsumirWS2();
    try {
        WS.Buscar();
    } catch (Exception ex) {
        Logger.getLogger(DialogCPF.class.getName()).log(Level.SEVERE, null, ex);
    }
    //...
    DialogCPF A = (DialogCPF) evt.getSource();
    A.dispose();

}

is unlikely to work, because it's unlikely that the source of the ActionEvent is going to be the dialog. I'm also concerned over the creation of an instance of ConsumirWS2, this isn't the responsibility of the dialog, the dialog should allow the caller to extract the information it needs, possibly via an observer pattern.

This...

dialog.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent e) {
        // Nothing
    }

    @Override
    public void keyPressed(KeyEvent e) {
        // Nothing 
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            //...
        }
    }
});

is a bad idea, for a number of reasons, apart from not been obvious to the user, any component which takes focus away from the dialog (like a text field) will prevent it from been executed. Instead, see How to set the Java default button to react on ENTER key _released_? for a better solution

But while we're here...

@Override
public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
        //...
        DialogCPF dialog = new DialogCPF(new javax.swing.JFrame(), true);
        //dialog.setEnabled(false);
        dialog.dispose();
    }
}

Isn't going to work. You create a new instance of the dialog and immediately dispose of it ... how is that going to have any affect on the instance of the dialog which is on the screen and triggered this event?!

Generally speaking, you need to call dispose on the current instance of the dialog and you might be better of looking at How to Make Dialogs and How to Make Frames and you'd most certainly be better off avoiding the use form editors

As a conceptual example...

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(50, 50, 50, 50));

            JButton btn = new JButton("Collect data");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    FormData formData = DataEntryPane.showDialog(TestPane.this, null);
                    if (formData != null) {
                        JOptionPane.showMessageDialog(TestPane.this, "I have new data");
                    } else {
                        JOptionPane.showMessageDialog(TestPane.this, "No new data for me");
                    }
                }
            });
            add(btn);
        }

    }

    public static class FormData {

        private String importantStuff;

        public FormData(String importantStuff) {
            this.importantStuff = importantStuff;
        }

        public String getImportantStuff() {
            return importantStuff;
        }

    }

    public static class DataEntryPane extends JPanel {

        public interface Observer {

            public void formValidationRequired(DataEntryPane source);
        }

        private Observer observer;
        private JTextField textField;

        public DataEntryPane(Observer observer, FormData formData) {
            this.observer = observer;
            setLayout(new GridBagLayout());
            textField = new JTextField(10);

            add(new JLabel("Some important stuff: "));
            add(textField);

            if (formData != null) {
                textField.setText(formData.getImportantStuff());
            }

            ActionListener actionListener = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (observer != null) {
                        observer.formValidationRequired(DataEntryPane.this);
                    }
                }
            };

            textField.addActionListener(actionListener);
        }

        public String getImportantStuff() {
            return textField.getText();
        }

        public static FormData showDialog(Component parent, FormData data) {
            enum State {
                OK, CANCEL
            }

            // You could use a JOptionPane instead, but where's the fun in that
            JDialog dialog = new JDialog(SwingUtilities.windowForComponent(parent));
            dialog.setTitle("All you data is belong to us");
            dialog.setModal(true);

            JPanel content = new JPanel(new BorderLayout());
            content.setBorder(new EmptyBorder(32, 32, 32, 32));
            dialog.setContentPane(content);

            DataEntryPane entryPane = new DataEntryPane(new Observer() {
                @Override
                public void formValidationRequired(DataEntryPane source) {
                    // Do what ever validation you need
                    boolean isValid = true;
                    if (isValid) {
                        source.putClientProperty("state", State.CANCEL);
                        dialog.dispose();
                    }
                }
            }, data);
            entryPane.setBorder(new EmptyBorder(32, 32, 32, 32));
            dialog.add(entryPane);

            JButton okayButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");

            okayButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    entryPane.putClientProperty("state", State.OK);
                    dialog.dispose();
                }
            });

            cancelButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    entryPane.putClientProperty("state", State.CANCEL);
                    dialog.dispose();
                }
            });

            JPanel actionPane = new JPanel();
            actionPane.setBorder(new EmptyBorder(8, 8, 8, 8));
            actionPane.add(okayButton);
            actionPane.add(cancelButton);

            dialog.add(actionPane, BorderLayout.SOUTH);
            dialog.getRootPane().setDefaultButton(okayButton);

            dialog.pack();
            dialog.setLocationRelativeTo(parent);
            dialog.setVisible(true);

            State state = (State) entryPane.getClientProperty("state");
            // Only process the information if the user selected "okay"
            if (state != null && State.OK == state) {
                System.out.println("Validate user input");
                // Do what ever validation you need
                boolean isValid = true;
                if (isValid) {
                    String importantStuff = entryPane.getImportantStuff();
                    return new FormData(importantStuff);
                }
            } else {
                System.out.println("User cancelled operation");
            }

            return null;
        }
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366