JFrame(或 JDialog)上的阻塞方法

问题描述 投票:0回答:1

我需要我的 readString 方法处于阻塞状态,直到用户将其文本输入到 TextArea 中。这是我的问题的模型:

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();
            }
        }
    }
}

我知道问题出在 while(...);但我举个例子。

这是主类:

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);
    }
}

我需要的是 readString 方法返回用户输入的字符串。方法原型无法更改。

要了解问题,您可以观看这些视频:

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

第一个显示 Console 类正是我希望它如何工作(事实上它工作得很好)。

第二个是相同的控制台类,但从另一个 JFrame 实例化。当前的实现通过 JOptionPane 获取用户输入,但我希望它的工作方式与第一个视频中所示的完全相同。

请帮助我。谢谢。

java swing jframe blocking edt
1个回答
0
投票

根据您给出的详细信息,我假设您希望 readString 在相应的用户输入不为空时返回用户输入,而且,我看到您每次按下特定按钮时都会调用该操作,因此,我认为您可以简单地检查和查看 userInput 是否为空。

//Example:
If (!UserInput.getText().isEmpty()) {
//code
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.