我遇到了一个问题,可能有一个简单的修复方法,但我似乎无法让它发挥作用。
我需要我的程序暂停或等待,直到用户选择跳过按钮或正/负反馈按钮,然后再继续。 我认为这需要基本的线程,但我不确定如何实现它。任何帮助将不胜感激。
gui显示在一个单独的类(GUI)中,其余的是另一个类。 该代码有点困惑,因为它是在 12 小时内为 Hackfest 编写的。
编辑:通过删除按钮监听器并使变量静态化,我自己解决了这个问题。
public void onStatus(Status status) {
//this is a listener from the Twitter4J class. Every time new Tweet comes in it updates.
for (int i = 0; i <= posWords.length; i++) {
if (status.getText().toLowerCase().contains(gui.sCrit.getText())
&& (status.getText().toLowerCase().contains(posWords[i].toLowerCase()))) {
//If the tweet matches this criteria do the following:
String tweet;
Status tempStoreP;
System.out.println("Flagged positive because of " +posWords[i].toLowerCase()+" " + i);
tempStoreP = status;
tweet = tempStoreP.getUser().getName() + ":" + tempStoreP.getText() + " | Flagged as positive \n\r";
gui.cTweet.setText(tweet);
//Write to log
try {
wPLog.append("~" + tweet);
} catch (IOException e) {
}
//Add action listeneer to gTweet.
//here is my problem. I want it to wait until a user has clicked one of these buttons before moving on and getting the next Tweet. It has to pause the thread until a button is clicked then it can only move on to getting another Tweet.
//the problem is that the button listener uses local variables to work.
gui.gTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (gui.pTweet.getText().equalsIgnoreCase("")) {
gui.pTweet.setText("Please type a response");
} else if (gui.pTweet.getText().equalsIgnoreCase("Please type a response")) {
gui.pTweet.setText("Please type a response");
} else {
try {
Status sendPTweet = twitter
.updateStatus("@" + tempStoreP.getUser().getScreenName() + " "
+ gui.pTweet.getText());
} catch (TwitterException e1) {
}
}
gui.gTweet.removeActionListener(this);
}
});
//add Aaction listert to sTweet
gui.sTweet.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
wPLog.append("Skipped \n\r");
} catch (IOException e1) {
}
gui.sTweet.removeActionListener(this);
}
});
}
感谢您的帮助。顺便说一句,如果有人能告诉我为什么当单击按钮时,它会循环并向人们发送相同消息的垃圾邮件,这将很有帮助。谢谢。
最佳答案
我考虑过多线程的事情,我认为它不够简单。 如果我是你,我会禁用除要单击的按钮之外的所有控件。
示例:
JButton button = new JButton( "Test );
button.setEnabled( false );
如果您只是禁用除按钮之外的所有控件,则在使用 button.setEnabled( true );
之前用户将无法单击该按钮。
关于java - 让程序等待直到单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37741701/