I'm trying to print a single image in a JFrame using JLabel with ImageIcon inside of it(as a part of slide-show like programme). Is it possible to rescale the image to fit the frame in real time?
(When you stretch the window the image should follow by rescaling, not necessarily keeping the proportions right).
Here's my code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
String path = args[0];
String time = args[1];
String size = args[2];
JLabel jl = new JLabel();
ImageIcon ii = null;
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(3);
File target = new File(path);
if (target.isDirectory()) {
File[] files = target.listFiles();
for (File file : files) {
if (is_Image(file)) {
try {
jl.setIcon(null);
ii = new ImageIcon(ImageIO.read(file));
jl = new JLabel(ii);
jl.setIcon(ii);
jf.add(jl);
jf.repaint();
jf.pack();
jf.setVisible(true);
try {
Thread.currentThread().sleep(Long.parseLong(time));
} catch (InterruptedException e) {
}
} catch (IOException e) {
}
} else {
jl.setIcon(null);
jl = new JLabel("Not an image");
jl.setFont(new Font("Serif", Font.PLAIN, size.charAt(0)));
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setVerticalAlignment(SwingConstants.CENTER);
jf.add(jl);
jf.repaint();
jf.pack();
jf.setVisible(true);
try {
Thread.currentThread().sleep(Long.parseLong(time));
} catch (InterruptedException e) {
}
jl.setText(null);
}
}
} else {
try {
ii = new ImageIcon(ImageIO.read(target));
} catch (IOException e) {
e.printStackTrace();
}
jl = new JLabel(ii);
jl.setIcon(ii);
jf.add(jl);
jf.repaint();
jf.pack();
jf.setVisible(true);
try {
Thread.currentThread().sleep(Long.parseLong(time));
} catch (InterruptedException e) {
}
}
jl = new JLabel("End of presentation");
jl.setFont(new Font("Serif", Font.PLAIN, size.charAt(0)));
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setVerticalAlignment(SwingConstants.CENTER);
jf.add(jl);
jf.repaint();
jf.pack();
}
public static boolean is_Image(File file) {
try {
return ImageIO.read(file) != null;
} catch (Exception e) {
return false;
}
}
}