我已经创建了ImagePanel
能够显示来自指定目录的图像-> 它休眠 1 秒并从 java 项目的目录加载下一个图像。它实际上加载了下一个图像,但不显示(它不刷新面板),当它完成目录中的所有文件时,它只显示目录中的最后一个图像。我想让它在加载每张图片后刷新。
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class Okno extends JFrame {
JPanel jp;
ImagePanel ImagePanel;
JButton buttonExit;
JButton buttonWyjscie;
public Okno() {
}
public void createGUI() {
setSize(400, 400);
setLayout(new GridLayout());
buttonExit = new JButton("Exit");
buttonWyjscie = new JButton("Wyjscie");
// Sluchacz sluchacz = new Sluchacz();
// buttonExit.addActionListener(sluchacz);
buttonExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
jp = new JPanel();
jp.setBorder(new LineBorder(new Color(40, 120, 80), 4));
ImagePanel = new ImagePanel();
ImagePanel.setBorder(new LineBorder(Color.blue, 4));
jp.add(buttonExit);
add(jp);
add(ImagePanel);
setVisible(true);
slajd();
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void slajd() {
try {
File f = new File(".");
File[] tablicaPlikow = f.listFiles();
for (File el : tablicaPlikow) {
String rozszerzenie = el.getName().substring(
el.getName().length() - 3);
if (rozszerzenie.equals("jpg") || rozszerzenie.equals("peg")) {
System.out.println(rozszerzenie);
ImagePanel.setImage(el);
}
repaint();
}
setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Okno().createGUI();
}
});
}
}
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private BufferedImage image;
public ImagePanel() {
}
public ImagePanel(String sciezka) {
setImage(new File(sciezka));
}
public void setImage(File plik) {
try {
image = ImageIO.read(plik);
System.out.println("tutaj");
repaint();
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
if (image != null) {
Image b = image.getScaledInstance(getWidth(), getHeight(),
Image.SCALE_FAST);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
}
}