Thread NullPointerException - java

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

Related

Why isn't the jumping animation showing?

I'm a beginner programmer and I recently started trying to make a game in Java.
It's very basic and doesn't include any classes (although it should) but anyway I tried to make a jumping animation on the JPanel using a JLabel as my sprite but whenever I try to time the space between each movement of the label by using Thread.sleep(millis) the Java seems to skip it and moves the label to the last position.
JFrame frame = new JFrame("malario");
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(700, 700);
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.blue);
JLabel malario = new JLabel("Malario");
malario.setOpaque(true);
malario.setBackground(Color.green);
panel.add(malario);
malario.setBounds(100, 550, 50, 50);
JLabel platform = new JLabel();
platform.setOpaque(true);
platform.setBounds(0,600,700,50);
panel.add(platform);
frame.setContentPane(panel);
frame.addKeyListener(new KeyListener() {
int originalx = 100;
int originaly = 550;
int currentlocx = originalx;
int currentlocy = originaly;
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==KeyEvent.VK_RIGHT){
malario.setBounds(currentlocx+10,currentlocy , 50, 50);
currentlocx = currentlocx+10;
}
if(e.getKeyCode()==KeyEvent.VK_LEFT){
malario.setBounds(currentlocx-10,currentlocy , 50, 50);
currentlocx = currentlocx-10;
}
int jumpy=0;
if(e.getKeyCode()==KeyEvent.VK_UP){
jumpy= currentlocy-100;
while(jumpy!=currentlocy){
malario.setBounds(currentlocx,currentlocy-10 , 50, 50);
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
currentlocy = currentlocy-10;
}
}
}
});
}
public static int Time(){
return (int)System.currentTimeMillis();
}
}
You can't use Thread.sleep().
All listener code is executed on the Event Dispatch Thread (EDT), which is the Thread responsible for handling events and painting the GUI. So, when you tell the Thread the sleep the GUI can't repaint itself until all the code in the loop has finished executing, so you only see the component at its last position.
Instead you need to use a Swing Timer to schedule the animation. Read the Swing Tutorial. There are sections on:
Concurrency in Swing- explains more about the EDT
How to Use Swing Timers - for examples on using a Timer
for more information.
Also, don't use a KeyListener. Instead it is better to use Key Bindings. The tutorial also has a section on How to Use Key Bindings.
Edit:
See: the KeyboardAnimation example from Motion Using the Keyboard for a working example that shows both:
how to use key bindings
how to do animation.

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
}

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.

BufferedImage in JFrame doesnt Show up

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");

Categories

Resources