Click event in a TextField conflicts as JOptionPane

5

I am learning how to create a sales system and I created this method to get information from a TextField and play within a table via the click of the enter button. I created a try-catch to handle exceptions, and if I enter the catch, it opens a JOptionPane. When I press enter again, the "%" button of JOptionPane is pressed by default.

However, when I click on enter to close the JOptionPane , it closes and reopens, because it is as if the TextField click event is activated, and ends up being a kind of loop, where every time the JOptionPane and the enter is pressed, it disappears and appears again.

How to solve this?

private void pegarConteudo(java.awt.event.KeyEvent e) {
    jLabelStatus.setText("Caixa Aberto");
    DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {//Verifica se a tecla ENTER foi pressionada 
        try {
            modelProdutos = controllerProdutos.retornarProdutosController(Integer.parseInt(jTextFieldPesquisa.getText()));
            modelo.addRow(new Object[]{
                modelo.getRowCount() + 1,
                modelProdutos.getIdProduto(),
                modelProdutos.getProdutoNome(),
                quantidade,
                modelProdutos.getProdutoValor(),
                modelProdutos.getProdutoValor() * quantidade
            });
            jTextFieldValorTotal.setText(somaValorTotal() + "");
            jTextFieldPesquisa.setText("");
            quantidade = 1;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Produto não cadastrado", "ERRO", JOptionPane.ERROR_MESSAGE);
            jTextFieldPesquisa.setText("");
        }
    }
    
asked by anonymous 17.05.2018 / 20:16

1 answer

5

Although you did not provide a snippet where you could play ( the hint for upcoming questions, always provide a Minimum, Complete, and Verifiable example ), I tested some probable hypotheses that might cause this and I ended up finding a situation that perfectly simulates the problem of the question:

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyEventTexFieldJOptionPaneTest extends JFrame {

    private JPanel contentPane;
    private JTextField textField;

    public static void main(String[] args) {
        EventQueue.invokeLater(KeyEventTexFieldJOptionPaneTest::new);
    }

    private Component getInstance() {
        return this;
    }

    public KeyEventTexFieldJOptionPaneTest() {

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(450, 300));
        contentPane = new JPanel(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JPanel panel = new JPanel();
        contentPane.add(panel, BorderLayout.NORTH);

        textField = new JTextField(10);
        textField.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                    System.out.println("enter pressionado e liberado");
                    JOptionPane.showMessageDialog(getInstance(), "teste");
                }
            }
        });
        panel.add(textField);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }
}

The cause here is just the method used to catch ENTER because keyReleased() is triggered when any key is released from the pressing. If you run the code, you will see that when you press ENTER in the text field, the modal will open, and if you press ENTER again, since the focus is on the OK button, this action will press this button and JOptionPane will be closed but the event will be fired in the text field again shortly after closing, causing it to be reopened, and if you keep pressing ENTER , this will continue to occur in a loop.

The demonstration below makes the explanation clearer:

Howtosolveitthen?

ThesimplestwaytoresolvewithoutoverridingoraddinganycomplexitiesinthecodeaboveistochangethemethodtokeyPressed(),whichistriggeredimmediatelyassoonasthekeyispressed.ButsincethemodalofJOptionPanestopstheexecutionoftherestofthescreenwhileitisbeingdisplayed,anditisonlycloseduntiltheOKbuttonisreleasedfromthepressing(ieuntil%init),whenyoupressENTERagain,itwillnotbecapturedbythetextfield.

Seethetestbelowwiththechange:

    
17.05.2018 / 20:47