Reputation: 365
I have a GUI form called SimpleGUI
that is just a single JPanel
. My goal is to display my URL image inside of the that JPanel
.
When I try to add the image, I don't get an error, but nothing displays. The image DOES display if I create a new JFrame
and add my JPanel
to that. But then I have two Windows open.
How can I display my image in my original SimpleGUI
form? (Code below)
Thank you!
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);
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);
}
}
Main method:
public class Main {
public static void main(String[] args) {
// write your code here
try {
SimpleGUI simpleGUI = new SimpleGUI();
} catch (IOException ioe){
ioe.printStackTrace();
}
}
}
Upvotes: 1
Views: 116
Reputation: 35011
This code at the top of your method should be at the end. This should fix the problem
setContentPane(imagesPanel);
pack();
setVisible(true);
Edit: As well as fixing the problem, I should have explained why this fixes the problem. The issue is when you called pack() at the beginning of the method, nothing has been added to the imagePanel, and so the return value of getPreferredSize()
is going to be very small / (0,0). After adding your Components, it can be sized appropriately
Upvotes: 3