【问题标题】:Setting ImageIcon to full screen将 ImageIcon 设置为全屏
【发布时间】:2020-02-01 20:14:02
【问题描述】:

我创建了一个 Board 类,我在其中使用 ImageIcon 导入图像,而不是制作具有指定分辨率的图片,我希望它对于任何类型的显示器都是全屏的。

public Board() {
        p = new Dude();
        addKeyListener(new AL());
        setFocusable(true);
        ImageIcon i = new ImageIcon("C:/test.jpg");

        img = i.getImage();
        time = new Timer(5, this);
        time.start();
    }

我以前用过这段代码:

public class MainMenu2 {
    MainMenu2() throws IOException{
        JFrame Main_Menu = new JFrame("Main Menu");
        Main_Menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        final int widthScreen = screenSize.width;
        final int heightScreen = screenSize.height;

        BufferedImage backgroundImage = ImageIO.read(new File("P://My Pictures//background1.jpg"));
        JLabel background = new JLabel(new ImageIcon(backgroundImage));
        Image scaleBackground = backgroundImage.getScaledInstance(widthScreen, heightScreen, Image.SCALE_SMOOTH);
        ImageIcon imageIcon = new ImageIcon(scaleBackground);
        Main_Menu.setContentPane(new JLabel(imageIcon));

使用缩放平滑,将图像设置为屏幕宽度和高度,但我不知道如何将其应用于我当前的代码。两者的区别在于,Board 类扩展了 JPanel,而 MainMenu2 只是一个普通类,其中创建了 JFrame 等。请帮助!谢谢。

【问题讨论】:

  • 您可以使用Stretch Icon。它将根据可用空间动态调整其大小。

标签: java image swing imageicon


【解决方案1】:

在最基本的层面上,它可能看起来像这样......

ImageIcon i = ImageIO.read(new File("C:/test.jpg"));
Image scaleBackground = backgroundImage.getScaledInstance(widthScreen, heightScreen, Image.SCALE_SMOOTH);            
img = scaleBackground.getImage();

现在,问题 - 组件的大小可能与屏幕的大小不匹配。

作为偏好,我可能会想做Scale the ImageIcon automatically to label size之类的事情

您还应该阅读The Perils of Image.getScaledInstance()

【讨论】:

  • 在我的代码中,我不使用 scaleBackground 那我为什么要应用它呢? scaleBackground 用于另一个不适用于我当前的代码示例,当类扩展 JPanel 时,我如何将 iage 设置为全屏?
  • @DennyS 首先——我把这两个例子都合并了——所以如果你尝试过,你可以直接将它应用到你JPanel 例子中。其次,您还可以查看我的答案中也链接的fully runnable example。在某个时候,您将采用这些示例并将其应用到您自己的工作流程中
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多