首页 > 解决方案 > 使代码在执行的操作中从同一位置继续

问题描述

    //boutton
    ent.setBounds(490,400,100,50);      
    ent.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {   
            String text;
            text=chatbox.getText().toLowerCase();
            chatarea.append("\t\t\t\t"+text+" <- YOU \n");
            chatbox.setText("");
            if(text.contains("hii") || text.contains("hey") ||  text.contains("hi"))
            {
                bot("hey there");
                bot("how can i help you?");
            }
            else if(text.contains("info") || text.contains("help") || text.contains("i need information") || text.contains("help me"))
            {
                bot("sure i am here to help you");
                bot("what you want to know about?");
                bot("1 info about anything?");
                bot("2 info about place?");
                bot("enter your choice : ");
                if(text.contains("1")|| text.contains("info about anything") || text.contains("number 1") || text.contains("first one") || text.contains("first"))
                {
                    bot("sure which blood group info you are looking for?");
                }else if(text.contains("2") || text.contains("info about place") || text.contains("number 2") || text.contains("second one") || text.contains("second"))
                else
                {
                    bot("I Don't Understand you");
                }
            }
        }
    });
}
private void bot(String string)
{
    chatarea.append("BOT -> "+string+"\n");
}
public static void main(String[] args)
{
    new bot();
}
} 

我正在制作一个聊天机器人,当我点击它时,JButton它会从中获取值JTextField并将其发布到JTextArea. 但问题是我希望我的代码继续而不是停止,但每次单击按钮它都会从启动代码开始。

当我第二次单击按钮时,如何使代码从相同的位置继续执行?

标签: javaswingjbutton

解决方案


向您的类添加一个布尔成员以bot跟踪状态(第一次/非第一次)并将其初始化为 true

boolean isFirstTimeButtonWasPressed = true

public void actionPerformed(ActionEvent e) {
    if (isFirstTimeButtonWasPressed) {
        //do stuff that should only happens the firs time   
        //...

        isFirstTimeButtonWasPressed = false;
    } 
    //do stuff that should be done every time the button is pressed
});

推荐阅读