如何从no-gui类实时更新Java Jframe控件 [英] How to update Java Jframe controls from no-gui class on real time
问题描述
我的Java JFrame项目有一个单调乏味的问题.
I have a tedious problem with my Java JFrame project.
我想做的(并寻找如何做的)是在不冻结我的应用程序的情况下,实时地从no-GUI类中将元素添加到我的ListBox
中,换句话说就是异步".这清楚吗?我尝试了SwingWorker
和Threads,但是没有结果.我所能做的就是在所有过程完成后更新列表框(显然,我的应用程序冻结了,因为我的过程很长).
What I want to do (and looking for how to) is add elements to my ListBox
from a no-GUI class in REAL TIME, or in other words "asynchronous", with out freezing my app. Is this clear? I tried SwingWorker
and Threads but without results. All I can do is update the listbox after all process finish (obviously with my app froze because my process is long).
这是我的体系结构:
这是我的代码(不起作用,只是为了理解)
And here is my code (not functional, just for understanding)
已编辑
视图(由NetBeans生成)
package view;
import com.everis.ingesta.controller.MyController;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
public class MyView extends javax.swing.JFrame {
public MyView(DefaultListModel<String> model) {
setVisible(true);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
btnRun = new javax.swing.JButton();
jscrlLog = new javax.swing.JScrollPane();
jlstLog = new javax.swing.JList();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
btnRun.setText("Run");
jscrlLog.setViewportView(jlstLog);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(159, 159, 159)
.addComponent(btnRun)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jscrlLog, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btnRun)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jscrlLog, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
public void addButtonListener(ActionListener listener) {
btnRun.addActionListener(listener);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MyView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyController();
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnRun;
private javax.swing.JList jlstLog;
private javax.swing.JScrollPane jscrlLog;
// End of variables declaration
}
控制器
package controller;
import business.MyBusiness;
import util.MyLog;
import view.MyView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MyController {
MyLog log;
MyBusiness business;
MyView view;
public MyController(){
log = new MyLog();
business = new MyBusiness(log.getLog());
view = new MyView(log.getLog());
}
public void runProcess() {
view.addButtonListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
business.runProcess();
}}
);
}
}
业务
package business;
import MyLog;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.SwingWorker;
public class MyBusiness {
private int counter = 0;
private DefaultListModel<String> model;
private MyLog log;
public MyBusiness(DefaultListModel<String> model) {
this.model = model;a
}
public void runProcess() {
SwingWorker<Void, String> worker = new SwingWorker<Void, String>() {
@Override
protected Void doInBackground() throws Exception {
for (int i = 0; i < 10; i++) {
publish("log message number " + counter++);
Thread.sleep(2000);
}
return null;
}
@Override
protected void process(List<String> chunks) {
// this is called on the Swing event thread
for (String text : chunks) {
model.addElement("");
}
}
};
worker.execute();
}
}
日志(型号)
package util;
import javax.swing.DefaultListModel;
public class MyLog {
private DefaultListModel<String> model;
public MyLog() {
model = new DefaultListModel<String>();
}
public DefaultListModel<String> getLog(){
return model;
}
}
推荐答案
这是一个长过程的过度简化示例,该过程生成String
值并使用SwingWorker
更新GUI.
This is an over-simplified example of a long-process generating String
values that update GUI using a SwingWorker
.
为了简化SwingWorker
的基本用法,对其进行了过度简化.
It is over simplified in an attempt to make the basic use of a SwingWorker
somewhat easier to follow.
这是一个文件 mcve ,这意味着您可以将整个代码复制粘贴到一个文件(MyView.java)中并执行:
This is a one-file mcve, meaning you can copy-paste the entire code into one file (MyView.java) and execute :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.SwingWorker;
//gui only, unaware of logic
public class MyView extends JFrame {
private JList<String> loglist;
private JButton log;
public MyView(DefaultListModel<String> model) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
log = new JButton("Start Process");
add(log, BorderLayout.PAGE_START);
loglist = new JList<>(model);
loglist.setPreferredSize(new Dimension(200,300));
add(loglist, BorderLayout.PAGE_END);
pack();
setVisible(true);
}
void addButtonListener(ActionListener listener) {
log.addActionListener(listener);
}
public static void main(String args[]) {
new MyController();
}
}
//represents the data (and some times logic) used by GUI
class Model {
private DefaultListModel<String> model;
Model() {
model = new DefaultListModel<>();
model.addElement("No logs yet");
}
DefaultListModel<String> getModel(){
return model;
}
}
//"wires" the GUI, model and business process
class MyController {
MyController(){
Model model = new Model();
MyBusiness business = new MyBusiness(model.getModel());
MyView view = new MyView(model.getModel());
view .addButtonListener(e -> business.start());
}
}
//represents long process that needs to update GUI
class MyBusiness extends SwingWorker<Void, String>{
private static final int NUMBER_OF_LOGS = 9;
private int counter = 0;
private DefaultListModel<String> model;
public MyBusiness(DefaultListModel<String> model) {
this.model= model;
}
@Override //simulate long process
protected Void doInBackground() throws Exception {
for(int i = 0; i < NUMBER_OF_LOGS; i++) {
//Successive calls to publish are coalesced into a java.util.List,
//which is by process.
publish("log message number " + counter++);
Thread.sleep(1000);
}
return null;
}
@Override
protected void process(List<String> logsList) {
//process the list received from publish
for(String element : logsList) {
model.addElement(element);
}
}
void start() {
model.clear(); //clear initial model content
super.execute();
}
}
这篇关于如何从no-gui类实时更新Java Jframe控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!