1
我試圖讓jpeg顯示在JFrame上,我注意到一些圖像文件可以工作,而另一些則不能。我使用的是Eclipse,我的所有圖像都在項目的根目錄中。當我運行調試器並且命中我的斷點時,它會將圖像上的imageheight和imagewidth報告爲-1,不會顯示圖像。它會在顯示的圖像上報告正確的值。ImageIcon方法不適用於所有圖像
起初我認爲它與圖像大小有關,但在mspaint中使用分辨率播放後,我意識到情況並非如此。
這裏是我到目前爲止的代碼:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import javax.imageio.*;
import java.io.File;
public class icon {
public static void main(String[] args) {
constructVNCForm();
}
public static void constructVNCForm() {
//Vars for GUI and essential layout code
final JFrame frame = new JFrame("This should be on top");
frame.setSize(800, 640);
Container content = frame.getContentPane();
frame.setVisible(true);
//image code here:
ImageIcon image = new ImageIcon("trial4.jpg");
//ABOVE WORKS
JLabel imageLabel = new JLabel(image);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
//add the image to the frame
content.add(imageLabel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content.setLayout(flow);
}
}
有任何的你有沒有和任何ImageIcons問題?我所有的jpegs都是300x300以下的各種尺寸。我對Java很陌生,所以如果你對我的代碼有任何建議,請告知。
當您嘗試使用'ImageIO'加載它們時會發生什麼?它比'ImageIcon'提供更多有用的反饋。如果字節很小(<100Kb),您也可以將其中一個問題圖像上傳到圖像共享網站並鏈接到它。 –
您應該將'frame.setVisible(true)'作爲最後一個語句放在'constructVNCForm'中。 – Reimeus
@Reimeus答案是正確的。 – vels4j