简体   繁体   English

从 SwingWorker 线程返回数组到主线程

[英]Return Array From SwingWorker Thread to Main Thread

I have a Swing GUI that when it open it performs aa thread in the background.我有一个 Swing GUI,当它打开时,它会在后台执行线程。 For that I used SwingWorker thread.为此,我使用了SwingWorker线程。 the problem is that I have an Array of String declare in main thread that is expected to collect information from swing worker thread and return that but after the thread is finishes the array is still empty.问题是我在主线程中有一个字符串数组声明,预计将从 swing 工作线程收集信息并返回,但在线程完成后,数组仍然为空。 I guess once the thread is finished the array looses its values even though the array is declare in the main thread.我猜一旦线程完成,即使在主线程中声明了数组,数组也会丢失它的值。

How can I return the values of the array to the main thread?如何将数组的值返回到主线程?

ArrayList<String> allnets = new ArrayList();
new SwingWorker<Object, Void>() {           
    @Override
    public Object doInBackground() throws SocketException, UnknownHostException {
        System.out.println("interfaces");
        netAdapter = new NetInterface();
        System.out.println(Thread.currentThread().getName());
        for(int i = 0; i < allnets.length; i++) {
            allnets.add("interface number");
        }
        return null;
    }

    @Override
    public void done() {                

    }   
}.execute();
System.out.println(Thread.currentThread().getName());
//      String[] inetfaces = {"eth0", "eth1", "wlan1", "wlan2", "wlan3"};
JComboBox comboBox = new JComboBox(allnets);
comboBox.setToolTipText("Interfaces");
comboBox.setBounds(444, 51, 137, 22);
frame.getContentPane().add(comboBox); 

To get the list of all interface names, call [static] method getNetworkInterfaces() of class java.net.NetworkInterface .要获取所有接口名称的列表,请调用 class java.net.NetworkInterface的 [静态] 方法getNetworkInterfaces() And I assume you want to call that method from inside a SwingWorker .我假设您想从SwingWorker内部调用该方法。 Also, from the code you posted, I assume you want to populate the JComboBox in the done() method of class SwingWorker .另外,根据您发布的代码,我假设您想在 class SwingWorkerdone()方法中填充JComboBox And since all the work is being done in the SwingWorker class, method doInBackground() doesn't need to return anything.由于所有工作都在SwingWorker class 中完成,因此方法doInBackground()不需要返回任何内容。

When it comes to using SwingWorker , I prefer to make a completely separate class that extends SwingWorker and not an anonymous inner class.在使用SwingWorker时,我更喜欢制作一个完全独立的 class 来扩展SwingWorker而不是匿名的内部 class。

Here is the code for a Swing application.这是Swing应用程序的代码。 The JFrame displays a JLabel and a JComboBox . JFrame显示一个JLabel和一个JComboBox The JcomboBox contains the list of the names of all the network interfaces. JcomboBox包含所有网络接口的名称列表。

Note that on my Windows 10 (64 bit) machine running JDK 13, populating the JComboBox takes hardly any time at all, so the SwingWorker is not really needed.请注意,在运行 JDK 13 的 Windows 10(64 位)机器上,填充JComboBox几乎不需要任何时间,因此不需要SwingWorker I guess you just want to practice using SwingWorker , correct?我猜你只是想练习使用SwingWorker ,对吗?

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;

public class SwngWrkr implements Runnable {
    private JComboBox<Object> combo;
    private JFrame frame;

    public void run() {
        showGui();
    }

    private JPanel createMainPanel() {
        JPanel mainPanel = new JPanel();
        mainPanel.add(new JLabel("Interfaces"));
        DefaultComboBoxModel<Object> model = new DefaultComboBoxModel<Object>();
        model.addElement("Loading...");
        combo = new JComboBox<Object>(model);
        mainPanel.add(combo);
        return mainPanel;
    }

    private void showGui() {
        frame = new JFrame("SW");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.add(createMainPanel(), BorderLayout.CENTER);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
        new GetIfTsk(combo).execute();
    }

    public static void main(String[] args) {
        SwngWrkr instance = new SwngWrkr();
        EventQueue.invokeLater(instance);
    }
}

class GetIfTsk extends SwingWorker<Void, Void> {
    private JComboBox<Object> combo;
    private List<Object> netIfNames;

    public GetIfTsk(JComboBox<Object> combo) {
        this.combo = combo;
        netIfNames = new ArrayList<>();
    }

    protected Void doInBackground() throws Exception {
        Enumeration<NetworkInterface> ifs = NetworkInterface.getNetworkInterfaces();
        int ndx = 0;
        while (ifs.hasMoreElements()) {
            NetworkInterface ni = ifs.nextElement();
            String name = ni.getName();
            System.out.printf("%2d. %s%n", ++ndx, name);
            netIfNames.add(name);
        }
        return null;
    }

    protected void done() {
        DefaultComboBoxModel<Object> model = (DefaultComboBoxModel<Object>) combo.getModel();
        model.removeAllElements();
        model.addAll(netIfNames);
        model.setSelectedItem(netIfNames.get(0));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM