簡體   English   中英

圖像未加載到JFrame內的JPanel中

[英]Image not loading in JPanel that is within a JFrame

我有一個JFrame,其中有4個不同的面板。 下圖右側的黑框是圖像面板。 我正在嘗試編寫一個類,該類將允許我將圖像加載到程序中任何其他類內的任何Panel中。

http://sdrv.ms/14TEq2T

LoadImage.java

package sf;

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

public class LoadImage extends Component {

BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImage(String filename) {
   try {         
       System.out.println(filename);
       img = new ImgUtils().scaleImage(380, 360, filename);           
   } catch (Exception e) {
       System.out.println("File not found");
   }

}

class ImgUtils {

    public BufferedImage scaleImage(int WIDTH, int HEIGHT, String filename) {
        BufferedImage bi = null;

        try {
            ImageIcon ii = new ImageIcon(filename);
            bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = (Graphics2D) bi.createGraphics();
            g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
            g2d.drawImage(ii.getImage(), 0, 0, WIDTH, HEIGHT, null);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return bi;
    }
}
}

我在其他類中用於加載Image的代碼。

private void getProductImage() {

    try {
        String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        String decodedPath = URLDecoder.decode(path, "UTF-8");
        String newPath = decodedPath.replace("build/classes/", "src/productImages/");

        productImagePanel.add(new LoadImage(newPath + imageCode + ".jpg"));
        revalidate();
        pack();


    } catch (Exception e) {
        e.printStackTrace();
    }
}

“ imageCode”是在“窗口”可見並且我多次檢查“圖像路徑”后從數據庫中檢索的代碼。

如果向其中添加了“ main runnable”方法,則LoadImage.java可以獨立工作並加載圖像,但是我似乎無法在所需的面板中顯示圖像。 請提出有關如何解決我的問題的建議,我們將不勝感激!

您的問題很可能是您正在嘗試將圖像作為組件加載到JPanel。 問題包括:

  • Component的preferredSize很可能是[0,0],因此可以嘗試顯示圖像有點費勁,但是太小了,無法顯示圖像。
  • JPanel中可能已經添加了其他組件
  • JPanel的布局可能不適用於新添加的組件。
  • 在沒有明確需要的情況下,請勿將重量較大的組件(組件)與重量輕的組件(大多數其他所有非頂層Window Swing組件)混合使用。

我建議:

  • 創建JPanel時,只需一次將JLabel添加到顯示JPanel的圖像即可。
  • 為您的productImagePanel提供一個接受Image或ImageIcon的方法,然后從該Image創建ImageIcon或使用提供的ImageIcon設置JLabel的圖標。
  • 確保JPanel使用允許JLabel完全顯示其自身的布局。 布局管理器教程可以對此提供幫助。
  • 顯示JPanel的圖像或全部圖像都是為了顯示圖像,而沒有其他內容,則放棄它,而是單獨使用JLabel,然后將圖標直接添加到其中。

順便提一句:您應該處置創建的任何Graphics和Graphics2D對象(而不是JVM給您的任何對象)。 這意味着當在ImageUtilities中使用g2d完成繪制后,將其丟棄。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM