【问题标题】:Make code continue from same place in action performed使代码在执行的操作中从同一位置继续
【发布时间】:2018-08-11 11:14:25
【问题描述】:
    //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。但问题是我希望我的代码继续而不是停止,但每次点击按钮都会启动代码。

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

【问题讨论】:

  • 检查问题标题。改进它。我无法理解它
  • 我已经改标题了
  • 看起来像一个带有布尔值的if else 或一个if else 用于检查文本区域是否有任何文本可以帮助你。
  • 基本上我想要的是当用户在 jtextbox 上写任何文本并单击 jbutoon 时,系统会自动响应该文本,但是当用户第二次按下 jbutoon 时,它会出现在我想要的顶部它不去开始 if else 我希望它继续 if else
  • 所以它是关于状态的。您需要一个成员变量来保存状态和逻辑以更改状态并根据当前状态采取行动

标签: java swing jbutton


【解决方案1】:

将布尔成员添加到您的 botclass 以跟踪状态(第一次/非第一次)并将其初始化为 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
});

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 2021-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    相关资源
    最近更新 更多