简体   繁体   English

当单击按钮从网络加载图像时,如何防止表单冻结?

[英]How do I prevent my form from freezing when it is loading an image from the web at the click of a button?

I want to display an image from the web to a panel in another Jframe at the click of a button but whenever I click the button first the image loads and during this time the current form potentially freezes and once the image has loaded the form is displayed with the image.. How can I avoid the situation where my form freezes since it is very irritating 我想通过单击按钮在Web上将图像显示到另一个Jframe中的面板,但是每当我第一次单击按钮时,图像就会加载,在此期间,当前表单可能会冻结,并且一旦图像加载,就会显示该表单与图像..如何避免表格冻结,因为它很烦人

My codes :: 我的代码::

My current class 我目前的课程

private void btn_TrackbusActionPerformed(java.awt.event.ActionEvent evt) {                                             
        try {
            sendMessage("Query,map,$,start,211,Arsenal,!");
            System.out.println(receiveMessage());
        } catch (UnknownHostException ex) {
            Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (Exception ex) {
            Logger.getLogger(client_Trackbus.class.getName()).log(Level.SEVERE, null, ex);
        }
        client_trackedbus nextform=new client_trackedbus(planform,connection,packet_receive,packet_send);
        this.setVisible(false);
        this.dispose();
        nextform.setVisible(true);
        // TODO add your handling code here:
    }                                            

My next class that displays the image 我的下一个显示图像的课程

public class client_trackedbus extends javax.swing.JFrame {
    client_planform planform=null;
    DatagramSocket connection=null;
    DatagramPacket packet_receive=null;
    DatagramPacket packet_send=null;
    JLabel label=null;
    /** Creates new form client_trackedbus */
    public client_trackedbus(client_planform planform,DatagramSocket 
        connection,DatagramPacket packet_receive,DatagramPacket packet_send) {
        initComponents();
        this.planform=planform;
        this.connection=connection;
        this.packet_receive=packet_receive;
        this.packet_send=packet_send;
        try {
            displayMap("http://www.huddletogether.com/projects/lightbox2/images/image-2.jpg", jPanel1, new JLabel());
        } catch (MalformedURLException ex) {
            Logger.getLogger(client_trackedbus.class.getName()).log(Level.SEVERE, null, ex);
        }

    }


    private void displayMap(String url,JPanel panel,JLabel label) throws MalformedURLException{
        URL imageurl=new URL(url);
        Image image=(Toolkit.getDefaultToolkit().createImage(imageurl));
        ImageIcon icon = new ImageIcon(image);
        label.setIcon(icon);
        panel.add(label);
       // System.out.println(panel.getSize().width);
        this.getContentPane().add(panel);
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        btn_Exit = new javax.swing.JButton();
        btn_Plan = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Public Transport Journey Planner");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 368, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 172, Short.MAX_VALUE)
        );

        jLabel1.setFont(new java.awt.Font("Arial", 1, 18));
        jLabel1.setText("Your tracked bus");

        btn_Exit.setText("Exit");
        btn_Exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ExitActionPerformed(evt);
            }
        });

        btn_Plan.setText("Plan journey");
        btn_Plan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_PlanActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(104, 104, 104)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(65, 65, 65)
                        .addComponent(btn_Plan)
                        .addGap(65, 65, 65)
                        .addComponent(btn_Exit, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_Exit)
                    .addComponent(btn_Plan))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void btn_ExitActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        Exitform();
    }                                        

    private void btn_PlanActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        this.setVisible(false);
        this.dispose();
         this.planform.setVisible(true);
    }                                        


    private void Exitform(){
        this.setVisible(false);
        this.dispose();

    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               // new client_trackedbus().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_Exit;
    private javax.swing.JButton btn_Plan;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration                   

}

you definitely need to use swingworker as trashgod suggested. 您绝对需要按照垃圾桶建议使用swingworker。 to make this connection clear, heres an example i strongly suggest you try out. 为了使这种连接更清晰,我强烈建议您尝试以下示例。 check "A More Complex Image Icon Example" in this link, and understand the code. 查看此链接中的“更复杂的图像图标示例”,并了解代码。 it perfectly solves your problem. 它完美地解决了您的问题。 http://download.oracle.com/javase/tutorial/uiswing/components/icon.html http://download.oracle.com/javase/tutorial/uiswing/components/icon.html

in particular, pay attention to this bit of code: 特别要注意以下代码:

 public IconDemoApp() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("Icon Demo: Please Select an Image");

    // A label for displaying the pictures
    photographLabel.setVerticalTextPosition(JLabel.BOTTOM);
    photographLabel.setHorizontalTextPosition(JLabel.CENTER);
    photographLabel.setHorizontalAlignment(JLabel.CENTER);
    photographLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    // We add two glue components. Later in process() we will add thumbnail buttons
    // to the toolbar inbetween thease glue compoents. This will center the
    // buttons in the toolbar.
    buttonBar.add(Box.createGlue());
    buttonBar.add(Box.createGlue());

    add(buttonBar, BorderLayout.SOUTH);
    add(photographLabel, BorderLayout.CENTER);

    setSize(400, 300);

    // this centers the frame on the screen
    setLocationRelativeTo(null);

    // start the image loading SwingWorker in a background thread
    loadimages.execute();
}

you can see in this constructor how event dispatch is occuring separately from loadimages.execute(), which uses the swingworker to load images in the background. 您可以在此构造函数中看到事件分发是如何与loadimages.execute()分开发生的,loadimages.execute()使用swingworker在后台加载图像。 i'll be happy to clarify any doubts. 我很乐意澄清任何疑问。

The form will freeze as soon as btn_TrackbusActionPerformed() is called. 一旦调用btn_TrackbusActionPerformed(),该表单将冻结。 The form will not unfreeze until btn_TrackbusActionPerformed() returns. 直到btn_TrackbusActionPerformed()返回时,表单才会解冻。

The solution is to have btn_TrackbusActionPerformed() start a thread and run all the code that is currently in btn_TrackbusActionPerformed() asynchronously on the new thread. 解决方案是让btn_TrackbusActionPerformed()启动一个线程,并在新线程上异步运行当前btn_TrackbusActionPerformed()中的所有代码。

Note that you will have thread safety issues when calling the Swing API on the new thread. 请注意,在新线程上调用Swing API时,您将遇到线程安全问题。

暂无
暂无

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

相关问题 如何防止我的JFrame冻结? - How do I prevent my JFrame from freezing? 在插件中使用JDialog时,如何防止冻结? - How do I prevent a JDialog from freezing when used in a plugin? Android表单验证-如何防止在按下按钮时空字段使我的应用程序崩溃? - Android Form Validation - How do I prevent a null field from crashing my application on button press? 2 问题:ArrayList 替代品? 当我的鼠标退出时,如何阻止我的线程冻结? - 2 Questions: ArrayList alternative? And how do I stop my Thread from freezing when my mouse exits? 当取消选中复选框或单选按钮时,如何阻止我的if语句更改值 - How do I prevent my if statement from changing the value when a check box or radio button is deselected 为了防止UI冻结我该怎么办(scheduledexecutorservice) - What should I do in order to prevent the UI from freezing(scheduledexecutorservice) 如何防止我的android中的“提交”按钮在多次单击时给我多个分数? - How do I prevent my submit button in android from giving me multiple scores when clicked multiple times? 如何在每次单击按钮时使用网络上的新图像刷新ImageVIew? - How to refresh ImageVIew on every button click with new image from the web? 如何从Web应用程序的根目录引用Java Web应用程序中的任何图像? - How do i refer to any image in my java web application from root of my web application? 如何防止“断管”取下我的tomcat网站? - How do I prevent “Broken pipe” from taking down my tomcat web site?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM