我制作了一个小型摇摆应用程序供我个人使用。此应用程序连接到互联网,检索文本文件,在 jTextArea 中显示其内容并将文本文件保存在本地(在我的硬盘中)。到现在为止还挺好。
现在我想以固定的定期间隔(比如每 30 秒后)接收这个文本文件。我可以通过 for/while 循环(和 thread.sleep 方法)来做到这一点,但我知道这不是正确的方法,因为它不允许我暂停/恢复接收。我尝试使用“线程”和“可调用”解决我的问题,但无法成功。(我对这些了解不多)
您能指导我如何从线程中收集字符串值吗?我在使用 Callable/Future 做正确的事吗?(请参阅我的代码)。我应该能够暂停/恢复文本收集。
(在暂停和恢复我的软件期间,我将进行一些手动文本编辑并将其保存到磁盘。但我可以处理。)
下面是我尝试过的代码。
public class AmybactUI extends javax.swing.JFrame {
public AmybactUI() {
initComponents();
}
private void initComponents() { .... }
public static void main(String args[]) throws Exception {
// (Look and feel setting code here)
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AmybactUI().setVisible(true);
}
});
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
List<Future<String>> results = executor.invokeAll(Arrays.asList(new GetScore()), 30, TimeUnit.SECONDS);
for (Future<String> result : results) {
if (!result.isCancelled()) {
jTextAreaOnlineScore.append(result.get()+"\n");
jTextAreaOnlineScore.setCaretPosition(jTextAreaOnlineScore.getDocument().getLength());
} else {
System.out.println("Task timed out.");
}
executor.shutdown();
}
}
// Variables declaration - do not modify
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JButton jButtonSaveSMS;
private javax.swing.JLabel jLabelTitle;
private javax.swing.JMenuBar jMenuBar;
private javax.swing.JMenu jMenuFile;
private javax.swing.JMenu jMenuHelp;
private javax.swing.JMenuItem jMenuItemAbout;
private javax.swing.JMenuItem jMenuItemExit;
private javax.swing.JMenuItem jMenuItemOptions;
private javax.swing.JMenu jMenuTools;
private javax.swing.JPanel jPanel;
private static javax.swing.JRadioButton jRadioButtonOffline;
public static javax.swing.JRadioButton jRadioButtonOnline;
private javax.swing.JScrollPane jScrollPane;
public static javax.swing.JTextArea jTextAreaOnlineScore;
private javax.swing.JTextField jTextFieldCustomSMS;
// End of variables declaration
}
class GetScore implements Callable<String> {
public String call() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String nextLine;
String myString = "";
String myTryString;
URL url;
URLConnection urlConn;
InputStreamReader inStream;
BufferedReader buff;
FileWriter fustream;
BufferedWriter bfout;
try {
// (some code here which connects to internet and gets my text)
} else {
break;
}
}
bfout.write(myString);
bfout.close();
} catch(MalformedURLException e) {
System.out.println("Please check the URL:" + e.toString());
} catch(IOException e1) {
System.out.println("Can't read from the Internet: " + e1.toString());
}
Thread.sleep(4000);
return (""+sdf.format(cal.getTime())+myString);
}
}