我有功能
public String namefunction(){
while(true){
StringBuilder a = new StringBuilder();
//do something
return a;
}
}
现在我想创建GUI和JButton。
但是,我想在每次循环后单击此按钮后从namefunction()
获得结果。我该怎么办?
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(myButton1)) {
tekst4.setText(namefunction());
}
}
答案 0 :(得分:1)
这是一个非常基本的示例,该示例使用SwingWorker
来接收和显示来自长while
循环的临时结果和最终结果。
(为了方便和简单起见,可以将整个代码复制粘贴到SwingMain.java
中并运行)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
public class SwingMain {
public static void creategui(){
JFrame f = new JFrame("SwingWorker Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.add(new TestPanel());
f.pack();
f.setVisible(true);
}
public static void main(String[] args) {
creategui();
}
}
class TestPanel extends JPanel {
private final DefaultListModel<String> listModel;
private MyWorker swingWorker;
private final JLabel finalResults;
private final JButton start;
TestPanel() {
setLayout(new BorderLayout(2, 2));
start = new JButton("Start");
start.addActionListener(e->start());
add(start, BorderLayout.PAGE_START);
listModel = new DefaultListModel<>();
JList<String> interimResults = new JList<>(listModel);
interimResults.setPreferredSize(new Dimension(150,200));
add(interimResults, BorderLayout.CENTER);
finalResults = new JLabel("- waiting for final results - ");
add(finalResults, BorderLayout.PAGE_END);
}
private void start() {
start.setEnabled(false);;
swingWorker = new MyWorker();
swingWorker.execute();
}
/*Class SwingWorker<T,V>
T - the result type returned by this SwingWorker's
doInBackground and get methods
V - the type used for carrying out intermediate results by this SwingWorker's
publish and process methods
*/
class MyWorker extends SwingWorker<String, String> {
//long process (work) is done in this method
@Override
protected String doInBackground() throws Exception {
int counter = 0;
StringBuilder result = new StringBuilder();
while(counter < 10){
result.append(String.valueOf(counter));
publish(result.toString()); //interim result
counter++;
Thread.sleep(500);
}
return result.toString(); //end result
}
//This method is processing List of interim "published" results
@Override
protected void process(List< String> chunks) {
for (String s : chunks) {
listModel.addElement(s);
}
}
//invoked when done
@Override
protected void done() {
try {
finalResults.setText("Final result: "+ get());
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
}
}
}