Sandra Leon
Sandra Leon

Reputation: 33

String and BufferedImage on JFrame

I am trying to display a string and a BufferedImage onto a JFrame that both come as output from a method. I am not able to separate the String from the image, therefore I need to add both to the JFrame.

Here is the code I have do far and nothing is displaying. Thank you very much for your help in advance.

String path = getUserInfo("abc123"); <-- method that returns a string and a buffered image
BufferedImage image = null;
try {
    image = ImageIO.read(new File(path));
} catch (IOException ex) {
    Logger.getLogger(InstagramClient.class.getName()).log(Level.SEVERE, null, ex);
}
JFrame f = new JFrame();
f.setSize(400,400);
f.setVisible(true);
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel(icon, JLabel.CENTER);
JOptionPane.showMessageDialog(null, label, "icon", -1);

Upvotes: 1

Views: 672

Answers (3)

Sandra Leon
Sandra Leon

Reputation: 33

Hovercraft Full Of Eels actually answered my question. I wanted to return both a String and BufferedImage but now I know that is not possible. Thank you all for your help :)

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347334

Basically, you can use the label's setText method to supply a text value for the label.

You also need to "add" the label to the frame, or it won't display anything.

String path = getUserInfo("abc123"); <-- method that returns a string and a buffered image
BufferedImage image = null;
try {
    image = ImageIO.read(new File(path));
} catch (IOException ex) {
    Logger.getLogger(InstagramClient.class.getName()).log(Level.SEVERE, null, ex);
}
JFrame f = new JFrame();
ImageIcon icon = new ImageIcon(image);
JLabel label = new JLabel("This is some text", icon, JLabel.CENTER);
f.add(label);
f.setVisible(true);

Upvotes: 3

trashgod
trashgod

Reputation: 205875

You can render the string over the image using drawString(), as shown here.

Alternatively, you can use label.setText() and rely on the label's horizontal & vertical alignment for positioning, as illustrated here.

Upvotes: 3

Related Questions