How to make two thread communicate through handler?

旧街凉风 提交于 2020-01-16 00:54:36

问题


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();
}  

回答1:


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:

  • 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.

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();
        }
    }
}

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();
            }
        }
    }
}


来源:https://stackoverflow.com/questions/33219408/how-to-make-two-thread-communicate-through-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!