gpt4 book ai didi

java - 如何让两个线程通过处理程序进行通信?

转载 作者:行者123 更新时间:2023-11-29 03:03:48 25 4
gpt4 key购买 nike

我有一个表单,当鼠标悬停在按钮上时,按钮可以自动调整其大小,并在鼠标退出时默认其大小。它第一次正常工作,但在我尝试了不止一次之后,它们的尺寸变大了,我无法正常控制。

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 调用(此处为 setIcon(...))违反了 Swing 线程完整性规则。话虽如此,为什么不通过以下方式简化所有这些:

  • 一次且仅一次读取、创建和存储您的 ImageIcons
  • 永远不要在您进行操作时忽略异常。这是不安全的编码。
  • 最重要的是,使用 Swing 计时器每 20 毫秒简单地交换一次图标,并且不用担心违反 Swing 线程规则。

你的 grow Timer 的 ActionListener 可以像这样简单:

// 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 看起来像这样:

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

你可以用类似这样的代码填充它:

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

还有一个更完整和可运行的例子:

Resizeable Icon

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

关于java - 如何让两个线程通过处理程序进行通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33219408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com