我正在尝试创建一个更改图片的面板。 这是我的小组:
public class AdvertisementPanel extends JPanel {
private BufferedImage image;
private ArrayList<String> pictures;
private int index = 0;
public AdvertisementPanel(String... pics) {
pictures = new ArrayList<String>(Arrays.asList(pics));
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
changeImage();
}
}, 0, 5, TimeUnit.SECONDS);
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
private void changeImage() {
String name = pictures.get(index);
try {
File input = new File(name);
image = ImageIO.read(input);
index++;
index %= pictures.size();
} catch (IOException ie) {
Logger.getLogger().log(Level.SEVERE,
"No adds found in given path: " + name);
}
}
我有一个框架,用于固定面板,但没有显示图片。 试图定期从框架重新绘制 - 引起一些有趣但不想要的结果...... 有什么想法吗?我究竟做错了什么?我该如何刷新框架的组件?
答案 0 :(得分:1)
每次更改图像时都需要重新绘制。
哦,它应该由swing事件处理线程来完成:
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
changeImage();
repaint();
}
};
}
}, 0, 5, TimeUnit.SECONDS);
更新更正其他一些问题
public class AdvertisementPanel extends JPanel {
private BufferedImage image;
private ArrayList<String> pictures;
private int index = 0;
public AdvertisementPanel(String... pics) {
pictures = new ArrayList<String>(Arrays.asList(pics));
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
changeImage();
}
}, 0, 5, TimeUnit.SECONDS);
}
private void changeImage() {
final BufferedImage img = nextImage();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
image = img;
repaint();
}
});
}
public void paint(Graphics g) {
if (image != null) {
g.drawImage(image, 0, 0, null);
}
}
private BufferedImage nextImage() {
String name = pictures.get(index);
try {
index++;
index %= pictures.size();
File input = new File(name);
return ImageIO.read(input);
} catch (IOException ie) {
Logger.getLogger("").log(Level.SEVERE,
"No adds found in given path: " + name);
return null;
}
}
}