有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java您能实时将ImageIcon重新缩放为JFrame吗?

我正在尝试使用JLabel在JFrame中打印一张图像,其中包含ImageIcon(作为类似幻灯片放映的程序的一部分)。是否可以实时重新缩放图像以适应帧

(拉伸窗口时,图像应随之重新缩放,不一定要保持正确的比例)

这是我的代码:

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

}
}

共 (0) 个答案