如何从类方法中重复创建 Jlabel addText?

发布于 2024-10-07 21:44:58 字数 9200 浏览 0 评论 0原文

我尝试了 swingwoker ,但它只会更新一次... http:// /piggyman007.blogspot.com/2010/04/java-swingworker-multithread.html

package smartOfficeJava;

import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Event;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.KeyStroke;
import java.awt.Point;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.SwingWorker;

import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToolBar;
import javax.swing.JTextArea;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.util.concurrent.ExecutionException;

public class GUI {
    smartOfficeJava.Arduino arduino = new smartOfficeJava.Arduino();  //  @jve:decl-index=0:
    private JFrame jFrame = null;
    private JPanel jContentPane = null;
    private JMenuBar jJMenuBar = null;
    private JMenu fileMenu = null;
    private JMenu helpMenu = null;
    private JMenuItem exitMenuItem = null;
    private JMenuItem aboutMenuItem = null;
    private JMenuItem saveMenuItem = null;
    private JDialog aboutDialog = null;
    private JPanel aboutContentPane = null;
    private JLabel aboutVersionLabel = null;
    private JMenu selectPort = null;
    private JMenuItem portName = null;
    private JLabel jLabel = null;
    /**
     * This method initializes jFrame
     * 
     * @return javax.swing.JFrame
     */


    SwingWorker worker = new SwingWorker<String, Void>() {
        //This method automatically gets executed in a background thread

        public String doInBackground() {

            //fetch the big list from the 

            String sens = arduino.getSensor();

            return sens;

        }
        //This methods automatically gets executed in the EDT

        public void done() {

            //Get method retuns the exect, same thing 

            //that the doInBackground() method returned
            String sens = null;
            try {
                sens = get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jLabel.setText(sens);
            //Now do all UI Operations here..
        }

        }; 







    private JFrame getJFrame() {
        if (jFrame == null) {
            jFrame = new JFrame();
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jFrame.setJMenuBar(getJJMenuBar());
            jFrame.setSize(300, 200);
            jFrame.setContentPane(getJContentPane());
            jFrame.setTitle("Application");
        }
        return jFrame;
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jLabel = new JLabel();
            jLabel.setBounds(new Rectangle(34, 20, 100, 38));
            jLabel.setText("JLabel");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(jLabel, null);
        }
        return jContentPane;
    }

    /**
     * This method initializes jJMenuBar    
     *  
     * @return javax.swing.JMenuBar 
     */
    private JMenuBar getJJMenuBar() {
        if (jJMenuBar == null) {
            jJMenuBar = new JMenuBar();
            jJMenuBar.add(getFileMenu());
            jJMenuBar.add(getHelpMenu());
            jJMenuBar.add(getSelectPort());
        }
        return jJMenuBar;
    }

    /**
     * This method initializes jMenu    
     *  
     * @return javax.swing.JMenu    
     */
    private JMenu getFileMenu() {
        if (fileMenu == null) {
            fileMenu = new JMenu();
            fileMenu.setText("File");
            fileMenu.add(getSaveMenuItem());
            fileMenu.add(getExitMenuItem());
        }
        return fileMenu;
    }

    /**
     * This method initializes jMenu    
     *  
     * @return javax.swing.JMenu    
     */
    private JMenu getHelpMenu() {
        if (helpMenu == null) {
            helpMenu = new JMenu();
            helpMenu.setText("Help");
            helpMenu.add(getAboutMenuItem());
        }
        return helpMenu;
    }

    /**
     * This method initializes jMenuItem    
     *  
     * @return javax.swing.JMenuItem    
     */
    private JMenuItem getExitMenuItem() {
        if (exitMenuItem == null) {
            exitMenuItem = new JMenuItem();
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
        }
        return exitMenuItem;
    }

    /**
     * This method initializes jMenuItem    
     *  
     * @return javax.swing.JMenuItem    
     */
    private JMenuItem getAboutMenuItem() {
        if (aboutMenuItem == null) {
            aboutMenuItem = new JMenuItem();
            aboutMenuItem.setText("About");
            aboutMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JDialog aboutDialog = getAboutDialog();
                    aboutDialog.pack();
                    Point loc = getJFrame().getLocation();
                    loc.translate(20, 20);
                    aboutDialog.setLocation(loc);
                    aboutDialog.setVisible(true);
                }
            });
        }
        return aboutMenuItem;
    }

    /**
     * This method initializes aboutDialog  
     *  
     * @return javax.swing.JDialog
     */
    private JDialog getAboutDialog() {
        if (aboutDialog == null) {
            aboutDialog = new JDialog(getJFrame(), true);
            aboutDialog.setTitle("About");
            aboutDialog.setContentPane(getAboutContentPane());
        }
        return aboutDialog;
    }

    /**
     * This method initializes aboutContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getAboutContentPane() {
        if (aboutContentPane == null) {
            aboutContentPane = new JPanel();
            aboutContentPane.setLayout(new BorderLayout());
            aboutContentPane.add(getAboutVersionLabel(), BorderLayout.CENTER);
        }
        return aboutContentPane;
    }

    /**
     * This method initializes aboutVersionLabel    
     *  
     * @return javax.swing.JLabel   
     */
    private JLabel getAboutVersionLabel() {
        if (aboutVersionLabel == null) {
            aboutVersionLabel = new JLabel();
            aboutVersionLabel.setText("Version 1.0");
            aboutVersionLabel.setHorizontalAlignment(SwingConstants.CENTER);
        }
        return aboutVersionLabel;
    }

    /**
     * This method initializes jMenuItem    
     *  
     * @return javax.swing.JMenuItem    
     */
    private JMenuItem getSaveMenuItem() {
        if (saveMenuItem == null) {
            saveMenuItem = new JMenuItem();
            saveMenuItem.setText("Save");
            saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
                    Event.CTRL_MASK, true));
        }
        return saveMenuItem;
    }

    /**
     * This method initializes selectPort   
     *  
     * @return javax.swing.JMenu    
     */
    private JMenu getSelectPort() {
        String [] ports= null;
        ports = arduino.listPorts();

        if (selectPort == null) {
            selectPort = new JMenu();
            selectPort.setText("port");
            for (String a : ports){
                selectPort.add(getPortName(a));
            }
        }
        return selectPort;
    }

    /**
     * This method initializes portName 
     *  
     * @return javax.swing.JMenuItem    
     */

    private JMenuItem getPortName(String port) {
        if (portName == null) {
            portName = new JMenuItem();
            portName.setText(port);
            try {
                arduino.connect(port);
                worker.execute();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return portName;
    }

    /**
     * Launches this application
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GUI application = new GUI();
                application.getJFrame().setVisible(true);
            }
        });

    }

}

I tried swingwoker , but it will update one time only ... http://piggyman007.blogspot.com/2010/04/java-swingworker-multithread.html

package smartOfficeJava;

import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Event;
import java.awt.BorderLayout;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.KeyStroke;
import java.awt.Point;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JButton;
import javax.swing.JRadioButton;
import javax.swing.SwingWorker;

import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JToolBar;
import javax.swing.JTextArea;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.util.concurrent.ExecutionException;

public class GUI {
    smartOfficeJava.Arduino arduino = new smartOfficeJava.Arduino();  //  @jve:decl-index=0:
    private JFrame jFrame = null;
    private JPanel jContentPane = null;
    private JMenuBar jJMenuBar = null;
    private JMenu fileMenu = null;
    private JMenu helpMenu = null;
    private JMenuItem exitMenuItem = null;
    private JMenuItem aboutMenuItem = null;
    private JMenuItem saveMenuItem = null;
    private JDialog aboutDialog = null;
    private JPanel aboutContentPane = null;
    private JLabel aboutVersionLabel = null;
    private JMenu selectPort = null;
    private JMenuItem portName = null;
    private JLabel jLabel = null;
    /**
     * This method initializes jFrame
     * 
     * @return javax.swing.JFrame
     */


    SwingWorker worker = new SwingWorker<String, Void>() {
        //This method automatically gets executed in a background thread

        public String doInBackground() {

            //fetch the big list from the 

            String sens = arduino.getSensor();

            return sens;

        }
        //This methods automatically gets executed in the EDT

        public void done() {

            //Get method retuns the exect, same thing 

            //that the doInBackground() method returned
            String sens = null;
            try {
                sens = get();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jLabel.setText(sens);
            //Now do all UI Operations here..
        }

        }; 







    private JFrame getJFrame() {
        if (jFrame == null) {
            jFrame = new JFrame();
            jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            jFrame.setJMenuBar(getJJMenuBar());
            jFrame.setSize(300, 200);
            jFrame.setContentPane(getJContentPane());
            jFrame.setTitle("Application");
        }
        return jFrame;
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jLabel = new JLabel();
            jLabel.setBounds(new Rectangle(34, 20, 100, 38));
            jLabel.setText("JLabel");
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(jLabel, null);
        }
        return jContentPane;
    }

    /**
     * This method initializes jJMenuBar    
     *  
     * @return javax.swing.JMenuBar 
     */
    private JMenuBar getJJMenuBar() {
        if (jJMenuBar == null) {
            jJMenuBar = new JMenuBar();
            jJMenuBar.add(getFileMenu());
            jJMenuBar.add(getHelpMenu());
            jJMenuBar.add(getSelectPort());
        }
        return jJMenuBar;
    }

    /**
     * This method initializes jMenu    
     *  
     * @return javax.swing.JMenu    
     */
    private JMenu getFileMenu() {
        if (fileMenu == null) {
            fileMenu = new JMenu();
            fileMenu.setText("File");
            fileMenu.add(getSaveMenuItem());
            fileMenu.add(getExitMenuItem());
        }
        return fileMenu;
    }

    /**
     * This method initializes jMenu    
     *  
     * @return javax.swing.JMenu    
     */
    private JMenu getHelpMenu() {
        if (helpMenu == null) {
            helpMenu = new JMenu();
            helpMenu.setText("Help");
            helpMenu.add(getAboutMenuItem());
        }
        return helpMenu;
    }

    /**
     * This method initializes jMenuItem    
     *  
     * @return javax.swing.JMenuItem    
     */
    private JMenuItem getExitMenuItem() {
        if (exitMenuItem == null) {
            exitMenuItem = new JMenuItem();
            exitMenuItem.setText("Exit");
            exitMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
        }
        return exitMenuItem;
    }

    /**
     * This method initializes jMenuItem    
     *  
     * @return javax.swing.JMenuItem    
     */
    private JMenuItem getAboutMenuItem() {
        if (aboutMenuItem == null) {
            aboutMenuItem = new JMenuItem();
            aboutMenuItem.setText("About");
            aboutMenuItem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JDialog aboutDialog = getAboutDialog();
                    aboutDialog.pack();
                    Point loc = getJFrame().getLocation();
                    loc.translate(20, 20);
                    aboutDialog.setLocation(loc);
                    aboutDialog.setVisible(true);
                }
            });
        }
        return aboutMenuItem;
    }

    /**
     * This method initializes aboutDialog  
     *  
     * @return javax.swing.JDialog
     */
    private JDialog getAboutDialog() {
        if (aboutDialog == null) {
            aboutDialog = new JDialog(getJFrame(), true);
            aboutDialog.setTitle("About");
            aboutDialog.setContentPane(getAboutContentPane());
        }
        return aboutDialog;
    }

    /**
     * This method initializes aboutContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getAboutContentPane() {
        if (aboutContentPane == null) {
            aboutContentPane = new JPanel();
            aboutContentPane.setLayout(new BorderLayout());
            aboutContentPane.add(getAboutVersionLabel(), BorderLayout.CENTER);
        }
        return aboutContentPane;
    }

    /**
     * This method initializes aboutVersionLabel    
     *  
     * @return javax.swing.JLabel   
     */
    private JLabel getAboutVersionLabel() {
        if (aboutVersionLabel == null) {
            aboutVersionLabel = new JLabel();
            aboutVersionLabel.setText("Version 1.0");
            aboutVersionLabel.setHorizontalAlignment(SwingConstants.CENTER);
        }
        return aboutVersionLabel;
    }

    /**
     * This method initializes jMenuItem    
     *  
     * @return javax.swing.JMenuItem    
     */
    private JMenuItem getSaveMenuItem() {
        if (saveMenuItem == null) {
            saveMenuItem = new JMenuItem();
            saveMenuItem.setText("Save");
            saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
                    Event.CTRL_MASK, true));
        }
        return saveMenuItem;
    }

    /**
     * This method initializes selectPort   
     *  
     * @return javax.swing.JMenu    
     */
    private JMenu getSelectPort() {
        String [] ports= null;
        ports = arduino.listPorts();

        if (selectPort == null) {
            selectPort = new JMenu();
            selectPort.setText("port");
            for (String a : ports){
                selectPort.add(getPortName(a));
            }
        }
        return selectPort;
    }

    /**
     * This method initializes portName 
     *  
     * @return javax.swing.JMenuItem    
     */

    private JMenuItem getPortName(String port) {
        if (portName == null) {
            portName = new JMenuItem();
            portName.setText(port);
            try {
                arduino.connect(port);
                worker.execute();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return portName;
    }

    /**
     * Launches this application
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                GUI application = new GUI();
                application.getJFrame().setVisible(true);
            }
        });

    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清泪尽 2024-10-14 21:44:58

done() 仅被调用一次,当 SwingWorker 线程完成时,您应该通过 doInBackground() 调用更新标签。一种可能的方法是实现 PropertyChangeListener 接口,如下所示:

public class MainFrame extends javax.swing.JFrame implements PropertyChangeListener {

    private final JLabel label = new JLabel();

    MainFrame() {

        setPreferredSize(new Dimension(200, 200));
        add(label);
        pack();

        SwingWorker worker = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                String c = null;
                for (String s : new String[] {"a", "b", "c"}) {
                    Thread.sleep(1000);
                    firePropertyChange("counter", c, c = s);
                }
                return true;
            }
        };

        worker.addPropertyChangeListener(MainFrame.this);
        worker.execute();
    }

    public void propertyChange(PropertyChangeEvent evt) {
        if ("counter".equals(evt.getPropertyName())) {
            label.setText((String) evt.getNewValue());
        }
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

}

done() is invoked only once, when SwingWorker thread is finished, you should update your label from doInBackground() call. One of possible ways is to implement PropertyChangeListener interface like this:

public class MainFrame extends javax.swing.JFrame implements PropertyChangeListener {

    private final JLabel label = new JLabel();

    MainFrame() {

        setPreferredSize(new Dimension(200, 200));
        add(label);
        pack();

        SwingWorker worker = new SwingWorker() {
            @Override
            protected Object doInBackground() throws Exception {
                String c = null;
                for (String s : new String[] {"a", "b", "c"}) {
                    Thread.sleep(1000);
                    firePropertyChange("counter", c, c = s);
                }
                return true;
            }
        };

        worker.addPropertyChangeListener(MainFrame.this);
        worker.execute();
    }

    public void propertyChange(PropertyChangeEvent evt) {
        if ("counter".equals(evt.getPropertyName())) {
            label.setText((String) evt.getNewValue());
        }
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

}
稍尽春風 2024-10-14 21:44:58

如果要处理 doInBackground() 方法的中间结果,您需要重写 SwingWorker 的 process() 方法。您可以通过从 doInBackground() 调用 publish() 方法来发布中间结果。

官方教程很好地解释了这一点。

You need to override process() method of SwingWorker, if you want to process intermediate results from the doInBackground() method. You can publish intermediate results by calling the publish() method from doInBackground().

The official tutorial explains this quite well.

一场信仰旅途 2024-10-14 21:44:58

我已经使用它解决了

class ShowSense extends JLabel implements Runnable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Thread th;
    public ShowSense(){
        th = new Thread(this);
        th.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true){
        String sens = arduino.getSensor();
        this.setText(sens);
        }

    }

}

I have solved it using

class ShowSense extends JLabel implements Runnable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private Thread th;
    public ShowSense(){
        th = new Thread(this);
        th.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true){
        String sens = arduino.getSensor();
        this.setText(sens);
        }

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文