Textfield click event conflicts like Joptionpane

Asked

Viewed 232 times

5

I am learning how to create a sales system and created this method to take information from a Textfield and play within a table by clicking the enter button. I created a Try-catch to handle exceptions and, if you enter the catch, opens a Joptionpane. When I press enter again, the "OK" button of JOptionPane is tight by default.

However, when I click enter to close the JOptionPane, it closes and opens again, as it is as if the Textfield click event was activated, and it ends up being a kind of loop, where every time the JOptionPane and the enter is tight, 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("");
        }
    }
  • 2

    Edit the question and submit a [mcve] p so it is possible to execute the code.

1 answer

4

Although you did not provide an excerpt where it was possible to reproduce(is the tip for next 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 precisely the method used to capture the ENTER, for the keyReleased() is fired when any key is released from pressing. If you run the code, you will see that when you press ENTER in the text field, the modal will open, and press ENTER again, as the focus is on the boot OK, this action will press this button and the JOptionPane will be closed but the event will be fired in the text field again soon after closing, causing it to be reopened, and if you continue pressing the ENTER, this will continue to occur in a loop.

The demonstration below makes the explanation clearer:

inserir a descrição da imagem aqui


How then?

The simplest way to resolve without altering too much or adding any complexities in the above code is to change the method to keyPressed(), which is fired immediately as soon as the key is pressed. But as the modal of the JOptionPane stops the execution of the rest of the screen while it is being displayed, and is only closed until the button OK is released from pressure (i.e., until the keyReleased() in it), when you press ENTER again, will not be captured by the text field.

See the test below with the change:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.