有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是等待字符串变为相等的正确方法

在Swing应用程序中,只有在用户输入正确答案后,方法才能继续。正确答案存储在String中,用户答案由侦听器设置为另一个String。所以,代码是

while (!correctAnswer.equals(currentAnswer)) {
     // wait for user to click the button with the correct answer typed into the textfield
}
// and then continue

这种方法一切都好吗?或者你会以某种方式重构它吗?它不会对CPU施加额外的惩罚吗? 这是一个有点similar question的例子


共 (5) 个答案

  1. # 1 楼答案

    是的,就像大家在这里说的

    对于gui应用程序,处理用户输入的最佳方法是等待触发事件

    然后可以使用一个方法来验证输入,如果成功,您可以继续流,这可以转到另一个页面

    下面是一个完整(但简单)的登录屏幕示例,它验证用户输入,如果成功,则执行一些操作

    此代码除了在一个完整的准备运行示例中显示如何应用此概念外,没有其他价值

    simple gui http://img229.imageshack.us/img229/1532/simplenz0.png

    // * used for brevity. Preffer single class per import
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.net.*;
    import java.io.*;
    
    
    public class MatchString{
    
        private final JTextField password;
        private final JFrame frame;
    
        public static void main( String [] args ){
            MatchString.show();
        }
    
        public static void show(){
            SwingUtilities.invokeLater( new Runnable(){
                public void run(){
                    new MatchString();
                }
            });
        }
    
        private MatchString(){
            password = new JPasswordField( 20 );
            frame = new JFrame("Go to www.stackoverflow");
            init();
            frame.pack();
            frame.setVisible( true );
        }
    
    
        private void init(){
    
            frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    
            frame.add( new JPanel(){{
                add( new JLabel("Password:"));
                add( password );
            }});
    
            // This is the key of this question.
            // the password textfield is added an 
            // action listener
            // When the user press enter, the method 
            // validatePassword() is invoked.
            password.addActionListener( new ActionListener(){
                public void actionPerformed( ActionEvent e ) {
                    validatePassword();
                }
            });
        }
    
    
        private void validatePassword(){            
            // If the two strings match
            // then continue with the flow
            // in this case, open SO site.    
            if ( "stackoverflow".equals(password.getText())) try {
                Desktop.getDesktop().browse( new URI("http://stackoverflow.com"));
                frame.dispose();
            } catch ( IOException ioe ){
                showError( ioe.getMessage() );
            } catch ( URISyntaxException use ){
                showError( use.getMessage() );
            } else {
                // If didn't match.. clear the text.
                password.setText("");
            }
        }
     }
    
  2. # 2 楼答案

    你是UI编程新手吗?我问你的原因是你的答案是基于一种程序化的编码风格,而这不是UI的目的。它往往是事件驱动的

    在这种情况下,解决方案非常简单:向submit按钮添加一个事件侦听器(ActionListener),并在那里检查结果。如果可以的话,继续。如果没有,就说出来,让他们再试一次

  3. # 3 楼答案

    正如其他人所建议的,您需要使用为按钮分配一个侦听器,按下按钮时将调用该侦听器

    下面是一个不完整的示例,演示了如何使用^{}并实现其^{}方法,该方法在按下按钮时被调用:

    ...
    final JTextField textField = new JTextField();
    final JButton okButton = new JButton("OK");
    okButton.addActionListner(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            if ("some text".equals(textField.getText()))
                System.out.println("Yes, text matches.");
            else
                System.out.println("No, text does not match.");
        }
    });
    ...
    

    您可能只想在按钮和文本字段所在的类中实现^{},因此不需要将这两个对象声明为final。(我只是使用了一个匿名的内部类来简化示例。)

    有关更多信息,您可能希望从The Java Tutorials查看How to Write an Action Listener

    另外,对于事件在Java中如何工作的一般信息,Java教程中的Lesson: Writing Event Listeners可能很有用

    编辑:根据Shinny先生和New先生的建议,将if语句中的表达式从textField.getText().equals("some text")更改为"some text".equals(textField.getText()),以防止NullPointerException如果textFieldnull

  4. # 4 楼答案

    如果您的字符串以GUI的速率来自人类用户,那么优化性能就没有什么意义了。人类每秒输入的字符串可能不会超过一到三个,而这对机器来说算不了什么

    在这个特殊的例子中,您需要做一些事情来获取要测试的输入,我建议使用do-while循环

  5. # 5 楼答案

    我想我不明白其中的逻辑,但它让我想起了过去的基本时代…:-)我不明白为什么应用程序强制用户键入已知的内容(除非是密码或其他内容)

    您编写的输入由侦听器观察。那么为什么不在那里进行测试呢?不要做等待事件的循环,让Java来做(和其他事情)。如有必要,将逻辑一分为二,当您检测到侦听器中给出了正确的输入时,转到第二部分

    我希望这是有意义的…;-)