How to show image in JFrame - java

Okay, this is likely to be flagged as a repeated question, but please hear me out first. I have looked all over the internet and have tried various ways to show an image in a JFrame, but nothing has worked for me. Is there any simple, foolproof! way to show an image in JFrame? Because if it's not foolproof, I'm sure to mess it up :/

You can try this out, I have commented what I have done and where to try and make it understandable and included a bit about resizing from this post. See how you get on :)
public class SO2 {
public static void main(String[] args) {
try {
//Step 1, read in image using javax.ImageIO
BufferedImage img = ImageIO.read(new File("D:/Users/user/Desktop/Tree.jpeg"));
//Optional, if you want to resize image this is an effective way of doing it
Image scaled = img.getScaledInstance(200, 200, Image.SCALE_SMOOTH);
//Step 2 create frame
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Step 3 add image to Frame
frame.add(new JLabel(new ImageIcon(scaled)));
//Step 4 Pack frame which sizes it around it's contents, then Show
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

How to overlap a JPanel(background) and a JTextField

I am creating a log in application for someones graduation, I need several text fields and a background, I have added the background and now need to add the text fields, the problem is that they won't seem to go on top of each other.
I have tried them each separately and without one another they both work perfectly but i can't get them to stack, I have seen several answers on this site to deal with a similar problem but for this application I need to put several text fields on the background as apposed to just one, here is what I have thus far...
//creates the frame with a title as a parameter
JFrame frame = new JFrame("Sign In Sheet");
//sets the size
frame.setSize(1000, 556);
//makes it so the application stops running when you close it
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//puts it in the center of the screen
frame.setLocationRelativeTo(null);
//makes it so you can't resize it
frame.setResizable(false);
//setting the background by looking for the image
try{
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
}catch(IOException e){
//and prints an error message if it's not found
System.out.println("well it didn't work");
}
//adding text fields with names apropriate to function
JTextField name1 = new JTextField();
name1.setPreferredSize(new Dimension(200, 15));
name1.setBackground(Color.WHITE);
frame.add(name1);
//makes frame visible
frame.setVisible(true);
Simply stated the text field won't show up with the background and all the results only offer answers for a single text field
The problem is in this line: frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Gabriel R. Warner/Desktop/clouds.png")))));
In this line you set a JLabel as the content pane of your JFrame. Then, you frame.add(name1); So you are adding a JTextField to a JLabel...Well this does not seem right, right?
The answer would be to create a new JPanel, add the background image to this panel, set the panel as the content pane of the frame and finally add the textfield to the panel/contentpane.
An example:
#SuppressWarnings("serial")
public class FrameWithBackgroundImage extends JFrame {
public FrameWithBackgroundImage() {
super("Sign In Sheet");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
try {
Image bgImage = loadBackgroundImage();
JPanel backgroundImagePanel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
};
setContentPane(backgroundImagePanel);
} catch (IOException e) {
e.printStackTrace();
}
JTextField textField = new JTextField(10);
add(textField);
}
private Image loadBackgroundImage() throws IOException {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File image = new File(desktop, "img.jpg");
return ImageIO.read(image);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new FrameWithBackgroundImage().setVisible(true);
});
}
}
Preview:
Worth to read question: Simplest way to set image as JPanel background

java.lang.NullPointerException when trying to display a ,gif file?

Well basically I tried to display a .gif using a url but it's given me a null pointer exception and I'm not really sure why since my url is correct and there's no other problems with my code(At least none that I can see).
import javax.swing.*;
import java.net.*;
public class image {
public image() {
}
public static void main(String[] args) {
URL url = image.class.getResource("<http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif>");
ImageIcon imageIcon = new ImageIcon(url);
JLabel label = new JLabel(imageIcon);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add(label);
frame.add(panel);
frame.setTitle("Title");
frame.setSize(700,500);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
URL url = image.class.getResource("<http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif>");
is not how you reference an image from a web resources. You would use this method to load resources that are embedded within your application (within the context of the applications classpath)
URL url = new URL("http://cdn.osxdaily.com/wp-content/uploads/2013/07/dancing-banana.gif");
would probably work better...
Remember, that downloading and loading the image may take some time, you may want to use a MediaTracker to track the progress, this would allow you to provide feedback to the user and know when to update the screen with the image once it's available, for example.
Before anyone asks, I choose not to use ImageIO to load an animated gif, because that is just a lot more work (as demonstrated here - not for the faint hearted). In this case, the MediaTracker could be used to check for errors

How to open an image using Imageicon on a jframe

I am trying to simply draw an image on a jframe by using an Imageicon. However when I run it its just blank. Heres my code...
public final class PICS
{
public static final void main(String... aArgs)
{
JFrame frame = new JFrame("IMAGE");
frame.setVisible(true);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
}
}
I am very new to everything java including this website, so I apologize if im missing something. Also im using Eclipse, and are there specific formats you can use for images, or is there a limit to size?
I am very new to everything java including this website
Then I would suggest you start by reading tutorials especially the Swing tutorial. Maybe the section on How to Use Icons would be a good place to start. The example code will show you how to use Icons as well as how to structure your program so that the GUI code is executed on the EDT. The tutorial on Concurrency will explain why the EDT is important.
Two things.
First, make setVisible the last call AFTER you have built your frame and it's contents...ie
JFrame frame = new JFrame("IMAGE");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon image = new ImageIcon("image/pic1.jpg");
JLabel label = new JLabel("", image, JLabel.CENTER);
JPanel panel = new JPanel(new BorderLayout());
panel.add( label, BorderLayout.CENTER );
// Make me last
frame.setVisible(true);
Two, make sure that the image/pic1.jpg exists and is the directory image under the current execution context.
If the image is a embedded resource (lives within the Jar or your application), then you need to supply a URL to the image instead of a String as ImageIcon treats String as a file name...
ImageIcon image = new ImageIcon(PICS.class.getResource("image/pic1.jpg"));
For example.
I would encourage you to use JFrame#pack over JFrame#setSize as it will resize the frame to the preferred size of your content...
I would also encourage you to take the time to read through Code Conventions for the Java Programming Language, Initial Threads.
I would also encourage you to use ImageIO over ImageIcon as it will, at least, throw an Exception if something goes wrong
Updated, testing image path
Try adding this to the constructor of your PICS class. This will, at least, tell you where the image isn't...
try {
ImageIO.read(PICS.class.getResource("image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in resources/image/pic1.jpg");
}
try {
ImageIO.read(PICS.class.getResource("/resources/image/pic1.jpg"));
} catch (IOException ex) {
System.out.println("Not in /resources/image/pic1.jpg");
}

Why JPanel repaint only once?

I want to create window where after 3 seconds image automatically will change.
This is my code:
JFrame frame=new JFrame();
pan pane= new pan();
frame.add(pane);
frame.setBounds(100, 100, 500, 500);
frame.setVisible(true);
try{
for(int i=0;i<returnedArray.size();i++){
pane.img=returnedArray.get(i).getFrontImage();
Thread.sleep(3000);
pane.repaint();
}
}catch(InterruptedException e){
e.printStackTrace();
}
class pan extends JPanel{
public Image img;
public void paint(Graphics g) {
g.drawImage( img, 0, 0, null);
}
}
...but I see last image all the time :(
I think that maybe JVM is improving my code?
How can I avoid this?
Maybe I am doing it wrong?
I will be very gratefull for any clue :)
Could your problem be this line in your for loop:
pane.img=returnedArray.get(2).getFrontImage();
which always selects the same image? Aside from this, you should probably use a Timer as pointed out in comments instead of using Thread.sleep

How to put a 800x600 image in a jLabel without having to scroll to see the whole image

i tried ways like getScaledInstance but all does not work. i could not find any solutions online either. the code that i am currently using is:
public class ShowImage_1 extends Panel {
BufferedImage image;
public ShowImage_1() {
try {
File input = new File("C:/Lighthouse.jpg");
image = ImageIO.read(input);
image.getGraphics().drawImage(image, 0, 0, 400, 400, null);
} catch (IOException ie) {
System.out.println("Error:" + ie.getMessage());
}
}
public void paint(Graphics g) {
g.drawImage(image, 0, 0, null);
}
static public void main(String args[]) throws Exception {
JFrame frame = new JFrame("Display image");
Panel panel = new ShowImage_1();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
it does not show the full image on the panel. any idea on how to go about doing it?
i want to achieve this effect: http://img209.imageshack.us/i/77894822.png/
but what i get now is this: http://img600.imageshack.us/i/19267006.png/
any other code i can use to get that?
Make the panel large enough to hold the image.. This may solve your problem
Add the image to a JLabel. Add the label to the frame. Then use:
frame.pack();
NOT
frame.setSize(800, 600);
If you need more help post your SSCCE demonstrating the problem.

Categories