代码非常简单。我从一个数组列表中得到一个URL字符串。然后我试图在我的JPanel中绘制图像。如果我没有在代码中初始化一个布局,它会返回一个错误。如果我初始化布局,则没有错误,但该图标也不显示。我错过了什么吗?谢谢!图片图标不显示在JPanel中
public class CharacterPage extends JFrame {
private JPanel imagesPanel;
private WikiDB wikiDB;
public CharacterPage(WikiDB db) throws IOException {
super("Character Page");
setContentPane(rootPanel);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(new Dimension(500,500));
imagesPanel.setLayout(new BorderLayout());
this.wikiDB = db;
searchButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ArrayList<String> characterImages =
wikiDB.searchImages(characterID);
//array contains this string: http://cosplayidol.otakuhouse.com/wp-content/uploads/2012/06/s-1-1.jpg
for (int x = 0; x < characterImages.size(); x++){
String imageURL = characterImages.get(x);
Graphics g = getGraphics();
try {
URL url = new URL(imageURL);
//icon.paintIcon(imagesPanel,g,300,100);
JLabel wIcon = new JLabel(new ImageIcon(url));
imagesPanel.setVisible(true);
imagesPanel.add(wIcon);
} catch (MalformedURLException mue){
mue.printStackTrace();
}
}
});
}
下面是我用来阅读我的URL的单独程序。使用下面的代码,我可以阅读我的URL而不会返回任何错误,但它仍然不会显示在GUI中。
public class SimpleGUI extends JFrame {
private JPanel imagesPanel;
public SimpleGUI() throws IOException {
super("GUI Page");
setContentPane(imagesPanel);
pack();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setSize(new Dimension(500, 500));
imagesPanel.setLayout(new GridLayout());
BufferedImage img1 = null;
try
{
URL url1 = new URL("http://cosplayidol.otakuhouse.com/wp-content/uploads/2012/06/s-1-1.jpg");
URLConnection conn1 = url1.openConnection();
conn1.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
InputStream in1 = conn1.getInputStream();
img1 = ImageIO.read(in1);
} catch (IOException e)
{
e.printStackTrace();
}
JLabel wIcon = new JLabel(new ImageIcon(img1));
imagesPanel.add(wIcon);
}
}
编辑:我正在在接近我现在可以弹出使用此代码包含图片的独立的框架:
public class SimpleGUI extends JFrame {
private JPanel imagesPanel;
private JFrame mainFrame;
public SimpleGUI() throws IOException {
super("GUI Page");
setContentPane(imagesPanel);
pack();
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(new Dimension(500, 500));
mainFrame = new JFrame();
imagesPanel.setLayout(new GridLayout());
imagesPanel.setBounds(0,0,200,200);
mainFrame.add(imagesPanel);
mainFrame.setVisible(true);
我似乎无法找到我的GUI原始帧窗体,所以我可以添加imagesPanel来代替。我正在使用IntelliJ的GUI表单构建器。
您需要调试 - 根本不需要读取图像工作吗?创建一个简单的GUI,其中一个读入Image(使用'ImageIO.read(URL url)'),创建一个ImageIcon并在JOptionPane中显示该图标。如果这有效,那么问题在别处。如果它不能纠正URL地址。 –
嗨Hovercraft,我能够创建一个简单的程序,纠正读取和显示图片,但我不能以原始的GUI形式/框架显示;我必须创建一个新的。我用新代码编辑了我的问题。有任何想法吗?谢谢! – Michelle
Michelle,新代码只显示您在新窗口中显示图片。直到您提炼出原始程序之前,我无法确定您的问题是什么。最好为你尝试创建并发布[最小代码示例](http://sscce.org)。 –