BufferedImage in JFrame doesnt Show up - java

trying to get an image to print into a window. Everything runs without errors, and it also works if I replace the drawImage with another graphics class. However, the window is missing the image, and i'm not sure why. Again, the JFrame stuff and Graphics work fine with drawing other graphics, but only doesn't draw the image here. Thanks.
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class GraphicsMovement2 extends JApplet{
BufferedImage image = null;
public static void main(String args[]){
BufferedImage image = null;
try {
File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
ImageInputStream imgInpt = new FileImageInputStream(file);
image = ImageIO.read(file);
}
catch(FileNotFoundException e) {
System.out.println("x");
}
catch(IOException e) {
System.out.println("y");
}
JApplet example = new GraphicsMovement2();
JFrame frame = new JFrame("Movement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(example);
frame.setSize(new Dimension(1366,768)); //Sets the dimensions of panel to appear when run
frame.setVisible(true);
}
public void paint (Graphics page){
page.drawImage(image, 100, 100, 100, 100, Color.RED, this);
}
}

You've defined image twice...
BufferedImage image = null;
public static void main(String args[]){
BufferedImage image = null;
This essentially means that by the time you get to the paint method, it is null as you haven't initialized the instance variable.
Another problem you will have is the fact that you are trying to load the image from a static reference but the image isn't declared as static. Better to move this logic into the constructor or instance method.
Don't use JApplet as your container when you're adding to a JFrame, you're better of using something like JPanel. It will help when it comes to adding things to the container.
YOU MUST CALL super.paint(g)...in fact, DON'T override the paint method of top level containers like JFrame or JApplet. Use something like JPanel and override the paintComponent method instead. Top level containers aren't double buffered.
The paint methods does a lot of important work and it's just easier to use JComponent#paintComponent ... but don't forget to call super.paintComponent
UPDATED
You need to define image within the context it is going to be used.
Because you declared the image as an instance field of GraphicsMovement2, you will require an instance of GraphicsMovement2 in order to reference it.
However, in you main method, which is static, you also declared a variable named image.
The paint method of GraphicsMovement2 can't see the variable you declared in main, only the instance field (which is null).
In order to fix the problem, you need to move the loading of the image into the context of a instance of GraphicsMovement2, this can be best achived (in your context), but moving the image loading into the constructor of GraphicsMovement2
public GraphicsMovement2() {
try {
File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
ImageInputStream imgInpt = new FileImageInputStream(file);
image = ImageIO.read(file);
}
catch(FileNotFoundException e) {
System.out.println("x");
}
catch(IOException e) {
System.out.println("y");
}
}
The two examples below will produce the same result...
The Easy Way
public class TestPaintImage {
public static void main(String[] args) {
new TestPaintImage();
}
public TestPaintImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
public ImagePane() {
setLayout(new BorderLayout());
ImageIcon icon = null;
try {
icon = new ImageIcon(ImageIO.read(new File("/path/to/your/image")));
} catch (Exception e) {
e.printStackTrace();
}
add(new JLabel(icon));
}
}
}
The Hard Way
public class TestPaintImage {
public static void main(String[] args) {
new TestPaintImage();
}
public TestPaintImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage background;
public ImagePane() {
try {
background = ImageIO.read(new File("/path/to/your/image"));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
}
}
}
}
Take the time to read through the tutorials
Creating a GUI With JFC/Swing
Performing Custom Painting

Your class shouldn't extend JApplet when you're not even using applets -- this makes no sense. Instead
Have your drawing class extend JPanel
Draw in the JPanel's paintComponent method
Add this JPanel to the JFrame's contentPane.
Read the Swing painting tutorials. You can't guess at this stuff and expect it to work, and the tutorials will show you how it's done correctly.

Don't mix file deviders,
File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
should be replaced with:
File file = new File("C:/Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");

Related

Using jWindow as splash screen which shows good but image doesn't paint ... just blank jWindow opened...any thoughts?

jWindow opened for 2 seconds but image doesn't paint... any thoughts?
image file is in the same folder as class file...
public class CreateSplashScreen extends JWindow {
JWindow jw = new JWindow();
Image scImage = Toolkit.getDefaultToolkit().getImage("testImage.png");
ImageIcon imageIcon = new ImageIcon(scImage);
public CreateSplashScreen() {
try {
jw.setSize(700, 500);
jw.setLocationRelativeTo(null);
jw.setVisible(true);
} catch (Exception e) {
}
}
public void paint(Graphics g) {
super.paint(g);
g.drawImage(scImage, 0, 0, jw);
}
public void CloseSplashScreen() {
jw.setVisible(false);
}
public static void main(String[] args) {
CreateSplashScreen sp = new CreateSplashScreen();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(CreateSplashScreen.class.getName()).log(Level.SEVERE, null, ex);
}
sp.CloseSplashScreen();
}
}
jWindow opened for 2 seconds but image doesn't paint... any thoughts?
image file is in the same folder as class file...
Why are you creating an internal JWindow when your class CreateSplashScreen already extends JWindow?
There is no need of it. You are messing with your program.
How?
You are actually viewing the inner JWindow by jw.setVisible(true); but you are painting the image in the CreateSplashScreen's `JWindow.
Try this code :
public class CreateSplashScreen extends JWindow
{
ImageIcon i = new ImageIcon(getClass().getResource("/createsplashscreen/testImage.png"));
public CreateSplashScreen() {
setSize(700, 500);
setLocationRelativeTo(null);
setVisible(true);
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(i.getImage(), 0, 0, null);
}
public void CloseSplashScreen() {
setVisible(false);
}
public static void main(String[] args) {
CreateSplashScreen sp = new CreateSplashScreen();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
sp.CloseSplashScreen();
}
}
Note: I do not know about your method to fetch image resource from the source folder.
Edit: Assuming that the name of the package containing your class CreateSplashScreen is createsplashscreen, make sure that the image testImage.png is present in the createsplashscreen package of your project.
#Peter
For error code, I deleted one line that I added in mamifest.mf file and build a program...
This time, didn't give me an error, weird...
I was following error code when I got it and it led me to something like "CLASSPATH" section of application generated code... sorry I can't remember exactly
Really appreciate Peter for your help.
Wish you luck...

Image in JFrame doesn't want to display with the call in another class

I work on a Java development software with Swing and I have a problem with my code, I want to display an image with the LoadingFrame class, its main work but when I call the constructor and the start() method in my main class, the frame opens but the image doesn't display (I have no Exception).
Why it doesn't work with my main class?
public class LoadingFrame
{
private JFrame frame;
public LoadingFrame()
{
frame = new JFrame();
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setUndecorated(true);
frame.setContentPane(new Panneau());
}
public void start()
{
frame.setVisible(true);
}
public void stop()
{
frame.setVisible(false);
}
public static void main(String[] args)
{
LoadingFrame l = new LoadingFrame();
l.start();
try
{
Thread.sleep(3000);
}
catch(Exception e)
{
e.printStackTrace();
}
l.stop();
}
}
public class Panneau extends JPanel
{
public void paintComponent(Graphics g)
{
System.out.println("hello");
try
{
Image img = ImageIO.read(new File("Images/loading.png"));
//g.drawImage(img, 0, 0, this);
//Pour une image de fond
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
The App class is my main class :
public class App {
//Attributes used to display the application
private JFrame frame;
//Attribute which display a waiting frame
private static LoadingFrame loadingFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
loadingFrame = new LoadingFrame();
loadingFrame.start();
App window = new App();
loadingFrame.stop();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public App()
{
initialize();
synchronizeScriptReferenceList();
synchronizeTests();
}
[...]
}
I was able to get this to work from App.java. For some reason, using EventQueue isn't cutting it. I tried to use SwingUtilities as well, but that doesn't work either. Finally I tried just get rid of the Thready-stuff in App.main at just straight up running it in the main thread. For some reason, this works when the other approaches do not! Here is my code:
// In the App class:
public static void main(String[] args) {
try {
loadingFrame = new LoadingFrame();
loadingFrame.start();
App window = new App();
loadingFrame.stop();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
When I used this code, I got it to work! (for some reason unknown to me), And here's a bonus rewrite of the Panneau class:
class Panneau extends JPanel
{
Image img;
public Panneau() {
try
{
img = ImageIO.read(new File("Images/loading.png"));
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
}
}
There are two main difference with this class; problems which I addressed. Here they are:
I call super.paintComponent as the very first method in our own paintComponent
I only load the loading image once, in the constructor, and not every single time I want to draw, which moves everything along much smoother. (you don't want the loading screen to be CPU heavy, do you?)
Hopefully, with these improvements, I hope you can make your program work! It worked with me, so I wish the best of luck to you.
P.S. Don't call frame.pack(), that was a mistake on my part. For some reason, I think it doesn't work well with undecorated windows.

How to load an image into a JPanel using Java

I would like to use an image as the background of a JPanel.
It needs to be loaded from a relative file path.
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JLabel background = new JLabel(new ImageIcon(backgroundImage));
this.add(background);
} catch(IOException e) {
System.out.println(e.toString());
}
}
My current code is not working. Any help would be appreciated.
So can't comment(need 50 rep) but your file path is completely wrong
you need it to be something like this
new File("C:/Users/"Insert Username"/Desktop/workspace/Java/BSC_Project/Application/src/resources/background.jpg")
except I'm not on your computer so you need to figure out your own file path, This would be assuming your workspace folder is on your Desktop which it almost certainly isn't, do you understand?
Well if you want your code to have a panel this is what you would do...
private void createBackground() {
try {
BufferedImage backgroundImage = ImageIO.read(new File("C:/Users/Developer/workspace/Java/BSC_Project/Application/src/resources/background.jpg"));
JPanel panel = new JPanel();
JLabel background = new JLabel(new ImageIcon(backgroundImage));
panel.add(background);
this.add(panel);
} catch(IOException e) {
System.out.println(e.toString());
}
}
but in your case it looks to me like you want a frame background as image... to which you can set the image background to which for that one you can try this code
JFrame f = new JFrame ("SettingBackGround");
try{
f.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("Med.jpg")))));
}catch (IOException e){
System.out.println("Image Doesnt Exist");
}
f.setVisible(true);
f.setResizable(false);
f.pack();
}
}
I hope this helps though.
public WelcomeView() {
initComponents();
try {
image = ImageIO.read(new File("C:\\Users\\Developer\\workspace\\Java\\BSC_Project\\Application\\src\\application\\resources\\background.png"));
} catch (IOException ex) {
System.err.println(ex.toString());
}
}
private BufferedImage image;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 2, 0, null); // see javadoc for more info on the parameters
}

Thread NullPointerException

Hey whenever i run this error output.
Exception in thread "Thread-2" java.lang.NullPointerException
at GraphicsTest.render(GraphicsTest.java:50)
at GraphicsTest.run(GraphicsTest.java:58)
at java.lang.Thread.run(Unknown Source)
here is the code i cant figure out why it will not work. i have searched online and cant seem to find any answers. i am new and just wanna draw an image to the screen. then maybe try and create a bufferedImage array later on but that is looking like it will be awhile down the road haha. thanks in advance for any help :)
public class GraphicsTest extends JPanel implements Runnable{
public static BufferedImage image;
private boolean isRunning = false;
public void start() {
isRunning = true;
new Thread(this).start();
}
public static void main(String args[]) {
GraphicsTest I = new GraphicsTest();
JFrame window = new JFrame("Test Rendering");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.setLocationRelativeTo(null);
window.setPreferredSize(new Dimension(600, 400));
window.pack();
window.setVisible(true);
I.start();
try {
image = ImageIO.read(new File("Grap/roby.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void render() {
Graphics g = getGraphics();
g.drawImage(image, 0, 0, null);
}
#Override
public void run() {
while(isRunning) {
render();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and just wanna draw an image to the screen
Try using something like...
GraphicsTest gt = new GraphicsTest();
try {
image = ImageIO.read(new File("Grap/roby.png"));
I.add(new JLabel(new ImageIcon(image));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JFrame window = new JFrame("Test Rendering");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(gt);
window.setLocationRelativeTo(null);
window.setPreferredSize(new Dimension(600, 400));
window.pack();
window.setVisible(true);
Take a look at How to Use Labels for more details.
Never use getGraphics to try and do custom painting, this is not how painting works in Swing.
If you're really intersted in knowing how painting works, take a look at Painting in AWT and Swing and Performing Custom Painting for more details.
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others

JPanel Not Opening When Instantiated From Other Class

In my main class, I call a class that, upon instantiation, should display its JFrame window. However, that is not the case. I've had this class work before, when I ran the project through Eclipse. Now, running it through command line, it does not work :(.
From my main method:
PaintTitleMovie q = new PaintTitleMovie();
The Jframe class:
public class PaintTitleMovie extends JPanel implements MouseListener {
Image image;
Font ConfettiFinal = new Font("Analog", 1, 20); // fail safe
static JFrame frame = new JFrame();
public PaintTitleMovie() {
image = Toolkit.getDefaultToolkit().createImage("src/Title2.gif");
try {
Font Confetti = Font.createFont(Font.TRUETYPE_FONT, new File(
"src/Fonts/Confetti.ttf"));
ConfettiFinal = Confetti.deriveFont(1, 50);
} catch (FontFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addMouseListener(this);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, this);
}
// draw exit button
g.setColor(Color.BLUE);
g.fillRect(990, 50, 210, 100);
g.setColor(Color.BLACK);
g.fillRect(1000, 60, 190, 80);
g.setColor(Color.WHITE);
g.setFont(ConfettiFinal);
g.drawString("Continue", 1000, 120);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.add(new PaintTitleMovie());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1200, 800);
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
SongTitle s = new SongTitle();
}
});
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
int x = arg0.getX();
int y = arg0.getY();
if (x >= 990 && y >= 50 && y <= 150) {
this.setVisible(false);
frame.dispose();
PaintMenu load = new PaintMenu(); // load paint menu
}
}
}
This src/Title2.gif is going to be problem, the src directory will not exist when the program is built.
Toolkit.getDefaultToolkit().createImage(String) also assumes that the resource is file on the file system, but anything that is contained within the application context (or jar file) is consider an embedded resource and can not be treated as a file.
Instead, you could need to use something more like
image = ImageIO.read(getClass().getResource("/Title2.gif"));
This will return a BufferedImage but will also throw an IOException if the image can not be loaded. If the gif is an animated gif you will need to use something more like
image = new ImageIcon(getClass().getResource("/Title2.gif"));
The same will go for your font, but in that case you will likely need to use
Font Confetti = Font.createFont(Font.TRUETYPE_FONT, getClass().getResourceAsStream(
"/Fonts/Confetti.ttf"));
If you're using Eclipse, you may need to move these resources out the the src directory and in a "resources" directory at the same level as the src directory in order for them to be included in the final build.

Categories

Resources