【问题标题】:Trying to display image on screen in Java, doesn't work尝试用 Java 在屏幕上显示图像,不起作用
【发布时间】:2013-12-23 07:28:00
【问题描述】:

我有两节课。 GUI 类扩展了JFrame,应该在屏幕上显示JPanel,这是扩展JPanel 的Surface 类。

Surface 类有一个应该显示图像的paintComponent 方法,但由于某种原因它不会显示它。代码如下:

import javax.swing.*;

public class GUI extends JFrame {

    GUI(){
        initUI();
    }

    public void initUI(){
        Surface s = new Surface();
        add(s);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[]args){
        GUI gui = new GUI();
        gui.setVisible(true);
    } 

} 

import java.awt.*; 
import javax.swing.*; 

public class Surface extends JPanel {

    Image image;
    ImageIcon ii;

    public void paintComponent(Graphics g) { 

        super.paintComponent(g); 

        Graphics2D g2d = (Graphics2D) g; 

        ii = new ImageIcon("redsquare.png"); 
        image = ii.getImage(); 

        Dimension d = new Dimension(); 
        d.width = image.getWidth(null); 
        d.height = image.getHeight(null); 
        this.setPreferredSize(d); 

        g2d.drawImage(image,50,50,null); 

    } 

} 

【问题讨论】:

  • 您的 png 文件在哪里?放到项目根目录下。
  • 永远不要在paintComponent中加载图像(ii = new ImageIcon("redsquare.png");),为此对象创建一个局部变量
  • 顺便说一句,这可以通过将图像显示在JLabel 和50px EmptyBorder 中来实现。

标签: java image swing embedded-resource imageicon


【解决方案1】:

您的文件位置似乎有问题,请尝试下一个从项目资源中获取 png 的代码:

ii = new ImageIcon(getClass().getResource("redsquare.png"));

对于该示例,redsquare.png 文件与 Surface 类位于同一包中。

【讨论】:

    【解决方案2】:

    如果您使用 Eclipse 或 Netbeans 等 IDE,使用此相对路径 "redsquare.png",您的图像需要直接位于项目根目录中

    ProjectRoot
             redsquare.png
             src
             bin
    

    另外,听听@mKorbel 的睿智话语

    “永远不要在paintComponent中加载图像(ii = new ImageIcon("redsquare.png");),为此对象创建一个局部变量” -@mKorbel

    另外,对于嵌入式资源,你真的应该考虑@alex2410 的回答。您想从类中加载图像。

    【讨论】:

      【解决方案3】:

      图片位置可能有问题 尝试使用不同的图像源运行

      【讨论】:

      • 我通常会说“这不是一个答案,但可能会做出很好的评论”。 OTOH 之前已在此线程中注意到,只是噪音。
      猜你喜欢
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      相关资源
      最近更新 更多