以下代码在屏幕上滑动一张卡片。当我关闭主窗口时,我希望事件调度线程也会关闭,但事实并非如此。关于为什么 ScheduledExecutorService 线程阻止 EDT 关闭的任何想法?
import java.awt.Graphics;
import java.net.URL;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Main extends JPanel
{
private float x = 1;
public void next()
{
x *= 1.1;
System.out.println(x);
repaint();
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
URL url = getClass().getResource("/209px-Queen_of_diamonds_en.svg.png");
g.drawImage(new ImageIcon(url).getImage(), (int) x, 50, null);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
final Main main = new Main();
frame.getContentPane().add(main);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
ScheduledExecutorService timer = Executors.newScheduledThreadPool(1, new ThreadFactory()
{
public Thread newThread(Runnable r)
{
Thread result = new Thread(r);
result.setDaemon(true);
return result;
}
});
timer.scheduleAtFixedRate(new Runnable()
{
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
main.next();
}
});
}
}, 100, 100, TimeUnit.MILLISECONDS);
}
}