如何使两个线程通过处理程序进行通信? [英] How to make two thread communicate through handler?

查看:67
本文介绍了如何使两个线程通过处理程序进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,当鼠标悬停在按钮上时,按钮可以自动调整其大小;退出鼠标时,按钮可以自动调整其大小.第一次可以正常使用,但是在尝试了不止一次之后,它们的尺寸被放大了,我无法正常控制.

I have form that button can auto re-size their size when mouse hover on button and default their size when mouse is exited. It work normally first time but after i try it more than one time their size is enlarged that i can not control normally.

ImageIcon ima=new ImageIcon("C:\\Users\\chen rina\\Pictures\\win.png");
ImageIcon icon;
Thread thr;
Runnable r=new Runnable() {
    @Override
    public void run() {
       int i=40;
        while(i!=80){
             try{
                 Thread.sleep(20);
     Image scale=ima.getImage().getScaledInstance(i,i,Image.SCALE_FAST);
                  icon=new ImageIcon(scale);
                  btn2.setIcon(icon);
                  i=i+5;
                }
             catch(Exception ex){}         
        }
    }
};

private void btn2MouseEntered(java.awt.event.MouseEvent evt) {                                  
    // TODO add your handling code here:
    thr=new Thread(r);
    thr.start();
}                                 

Runnable res=new Runnable() {
      int i;
    @Override
    public void run() {
       int i=80;
        while(i!=40){
             try{
                  Thread.sleep(20);
 Image scale=ima.getImage().getScaledInstance(i,i,Image.SCALE_AREA_AVERAGING);
                   icon=new ImageIcon(scale);
                    btn2.setIcon(icon);
                    i=i-5;
                }
               catch(Exception ex){}         
        }
    }
};

private void btn2MouseExited(java.awt.event.MouseEvent evt) {                                 
         thr=new Thread(res);
         thr.start();
}  

推荐答案

您的代码通过在后台状态下进行Swing调用而违反了Swing线程完整性规则,此处为setIcon(...).话虽如此,为什么不通过以下方式简化所有这些操作:

Your code violates Swing thread integrity rules by making Swing calls, here setIcon(...) from within a background state. Having said that, why not simplify all of this by:

  • 仅一次读取并创建和存储ImageIcons
  • 从不在执行操作时会忽略异常.那是不安全的编码.
  • 最重要的是,使用Swing计时器每20毫秒简单地交换图标,而不必担心会违反Swing线程规则.
  • Reading in and creating and storing your ImageIcons once and only once
  • Never ignore exceptions as you're doing. That's unsafe coding.
  • Most important, use a Swing Timer to simply swap icons every 20 msec, and have no fear about violating Swing threading rules.

您的成长计时器的ActionListener可以像这样简单:

Your grow Timer's ActionListener could be as simple as this:

// a private inner class
private class GrowListener implements ActionListener {
    private int index = 0;

    @Override
    public void actionPerformed(ActionEvent e) {
        // assuming the button is called button and the list iconList
        button.setIcon(iconList.get(index));
        index++;

        if (index >= iconList.size()) {
            ((Timer) e.getSource()).stop();
        }
    }
}


iconList类似于:


The iconList would look something like:

private List<Icon> iconList = new ArrayList<>();

您可以用类似于以下内容的代码填充它:

And you could fill it with code looking something like:

for (int i = startLength; i <= endLength; i += step) {
    Image img = originalImg.getScaledInstance(i, i, Image.SCALE_FAST);
    iconList.add(new ImageIcon(img));
}

还有一个更完整,更可运行的示例:

And a more complete and runnable example:

import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class ResizeIconTest extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private static final int START_LENGTH = 40;
    private static final int END_LENGTH = 120;
    private static final int STEP = 5;
    private static final int TIMER_DELAY = 20;
    private static final String URL_SPEC = "https://upload.wikimedia.org/wikipedia/commons/"
            + "thumb/2/2b/Oryx_gazella_-_Etosha_2014_square_crop.jpg/"
            + "600px-Oryx_gazella_-_Etosha_2014_square_crop.jpg";
    private JButton button = new JButton();
    private ResizeIcon resizeIcon;

    public ResizeIconTest() throws IOException {
        add(button);

        URL imageUrl = new URL(URL_SPEC);
        BufferedImage originalImg = ImageIO.read(imageUrl);
        resizeIcon = new ResizeIcon(button, originalImg, START_LENGTH,
                END_LENGTH, STEP, TIMER_DELAY);
        button.setIcon(resizeIcon.getSmallestIcon());

        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                resizeIcon.grow();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                resizeIcon.shrink();
            }
        });
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        ResizeIconTest mainPanel = null;
        try {
            mainPanel = new ResizeIconTest();
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }

        JFrame frame = new JFrame("ResizeIconTest");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

class ResizeIcon {
    private List<Icon> iconList = new ArrayList<>();
    private AbstractButton button;
    private int delayTime;
    private Timer growTimer;
    private Timer shrinkTimer;

    public ResizeIcon(AbstractButton button, BufferedImage originalImg,
            int startLength, int endLength, int step, int delayTime) {
        this.button = button;
        this.delayTime = delayTime;

        for (int i = startLength; i <= endLength; i += step) {
            Image img = originalImg.getScaledInstance(i, i, Image.SCALE_FAST);
            iconList.add(new ImageIcon(img));
        }
    }

    public Icon getSmallestIcon() {
        return iconList.get(0);
    }

    public void grow() {
        if (growTimer != null && growTimer.isRunning()) {
            return; // let's not run this multiple times
        }

        if (button.getIcon() == iconList.get(iconList.size() - 1)) {
            return; // don't run if already at largest size
        }

        growTimer = new Timer(delayTime, new GrowListener());
        growTimer.start();
    }

    public void shrink() {
        if (shrinkTimer != null && shrinkTimer.isRunning()) {
            return; // let's not run this multiple times
        }

        if (button.getIcon() == iconList.get(0)) {
            return; // don't run if already at smallest size
        }

        shrinkTimer = new Timer(delayTime, new ShrinkListener());
        shrinkTimer.start();
    }

    private class GrowListener implements ActionListener {
        private int index = 0;

        @Override
        public void actionPerformed(ActionEvent e) {
            button.setIcon(iconList.get(index));
            index++;

            if (index >= iconList.size()) {
                ((Timer) e.getSource()).stop();
            }
        }
    }

    private class ShrinkListener implements ActionListener {
        private int index = iconList.size() - 1;

        @Override
        public void actionPerformed(ActionEvent e) {
            button.setIcon(iconList.get(index));
            index--;

            if (index < 0) {
                ((Timer) e.getSource()).stop();
            }
        }
    }
}

这篇关于如何使两个线程通过处理程序进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆