user3216993
user3216993

Reputation: 1

Blocking method on a JFrame (or JDialog)

I need that my readString method be blocking until user input his text into the TextArea. This is a model of my problem:

public class Consola
{
    private final JDialog dialog;
    private final JTextArea textArea;
    private String userInput; 
                                        
    public Consola(JFrame mainFrame)
    {
        dialog=new JDialog(mainFrame);
        textArea=new JTextArea();
        textArea.addKeyListener(new EscuchaKey());
        dialog.add(new JScrollPane(textArea),BorderLayout.CENTER);

        dialog.setSize(300,300);
        dialog.setVisible(true);
    }

    public String readString() 
    {
        // Resetear el estado
        userInput=null;
        textArea.setText("");
        
        while(userInput==null)
        {
        }
        
        return userInput;
    }

    class EscuchaKey extends KeyAdapter
    {
        @Override
        public void keyPressed(KeyEvent e)
        {
            if(e.getKeyCode()==KeyEvent.VK_ENTER)
            {
                userInput=textArea.getText().trim();
            }
        }
    }
}

I konw that the problem where is while(...); but I put it as example.

Here is the main class:

public class ConsolaTest {
    public static void main(String[] args) {
        // Crear un JFrame principal
        JFrame mainFrame = new JFrame("Test Consola");
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setSize(300,300);
        
        JButton button = new JButton(":O)");
        mainFrame.add(button,BorderLayout.WEST);

        Consola consola = new Consola(mainFrame);
        
        // Acción del botón
        button.addActionListener(e -> {
            String input = consola.readString();
            System.out.println("Texto ingresado: " + input);
        });

        mainFrame.setVisible(true);
    }
}

What I need is that readString method return the string inputed by the user. The method prototy can not be changed.

To understand the problem you can watch these videos:

https://youtube.com/playlist?list=PLjYxSENnzyZltzpXd2_7azTYRu0QEOZbf&si=m2ZF2tZz3GrN-B81

The first shows the Console class exactly how I want it to work (in fact it works fine).

The second is the same console class but instantiated from another JFrame. The current implementation takes user input via JOptionPane, but I want it to work exactly the same as shown in the first video.

Please, help me. Thank.

Upvotes: 0

Views: 131

Answers (0)

Related Questions