I was trying out putting images in java. My end goal is to make a image I can control with arrow keys, but I can't seem to put an image in. I imported the image, and I have the name correct. I keep getting a null pointer exception.
code:
import java.awt.*;
import javax.swing.*;
public class Test extends JPanel {
public static ImageIcon image;
public void paintComponent(Graphics g) {
super.paintComponent(g);
image = new ImageIcon(getClass().getResource("rocketJava.jpg"));
image.paintIcon(this,g, 20, 20);
}
public static void main(String[] args) {
JFrame f= new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Test s = new Test();
f.add(s);
f.setSize(600,600);
f.setVisible(true);
}
}
The problem was just that I needed to move the picture file to the bin folder.
Related
The problem is that the image is not getting loaded while I run the following swing program.
I have a package called "sWINGPRAC" inside which I have a JAVA file IconLabelDemo.java. I have ensured that the Image "myIcon.gif" is in the same directory.
IconLabelDemo.java.
package sWINGPRAC;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class IconLabelDemo {
public IconLabelDemo() {
JFrame jfrm = new JFrame("ImageIcon");
jfrm.getContentPane().setLayout(new GridLayout(4, 1));
jfrm.setSize(250, 300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("myIcon.gif");
JLabel jlabIcon = new JLabel(img);
JLabel jlabIconTxt = new JLabel("Default iCon and text position",img , SwingConstants.CENTER);
JLabel jlabIconTxt2 = new JLabel("Text left of icon",img,SwingConstants.CENTER);
jlabIconTxt2.setHorizontalTextPosition(SwingConstants.LEFT);
JLabel jlabIconTxt3 = new JLabel("Text Over ICon",img,SwingConstants.CENTER);
jlabIconTxt3.setVerticalTextPosition(SwingConstants.TOP);
jfrm.add(jlabIcon);
jfrm.add(jlabIconTxt);
jfrm.add(jlabIconTxt2);
jfrm.add(jlabIconTxt3);
jfrm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new IconLabelDemo();
}
});
}
}
Nadir has hit the nail on the head with his comment. You are using "myIcon.gif" as a filename, which means it has to be local to the directory where the program is executed. If you want to package the icon with your library, you need to look into using resource loaders. Have a look at this question: How to correctly get image from 'Resources' folder in NetBeans (it should apply in Eclipse also).
Here you will see my code:
I am just trying to make a little window that displays "Hello, Java!".
I am currently running on Ubuntu 14.04. To go more in depth with my problem, the icon with the coffee cup shows up when I run the program like there is a window, but there is not window attached to it and if clicked, no window pops up.
Any help would be much appreciated!
public class HelloJava1 extends javax.swing.JComponent
{
public static void main(String[] args)
{
javax.swing.JFrame f = new javax.swing.JFrame("HelloJava1");
f.setSize(300, 300);
f.getContentPane().add(new HelloJava1());
f.setVisible(true);
}
public void paintComponent(java.awt.Graphics g)
{
g.drawString("Hello, Java!", 125, 95);
}
}
Additionally, I am compiling via command line using javac HelloJava1.java and running using java HelloJava1.
I am writing the code via gedit.
This code should work reliably:
import java.awt.*;
import javax.swing.*;
public class HelloJava1 extends JComponent {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JFrame f = new JFrame("HelloJava1");
// f.setSize(300, 300); better to pack() the frame
f.getContentPane().add(new HelloJava1());
// pack should be AFTER components are added..
f.pack();
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
SwingUtilities.invokeLater(r);
}
#Override // good practice..
public void paintComponent(java.awt.Graphics g) {
// always call super method 1st!
super.paintComponent(g);
g.drawString("Hello, Java!", 125, 95);
}
// instead of setting the size of components, it is
// better to override the preferred size.
#Override
public Dimension getPreferredSize() {
return new Dimension(300,300);
}
}
I have been trying to upload an image onto a Java Applet Window but unfortunately it turns out to be blank..Here is the code i have written pls help!
import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
import java.net.*;
import java.util.*;
public class RandomImages extends JFrame
{
private Image img;
public void static main(String[] args)
{
new RandomImages();
}
public RandomImages()
{
super("Random Images");
setSize(450,450);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Toolkit tk=Toolkit.getDefaultToolkit();
img=tk.getImage(getURL("Your File Name"));
}
Below is the code that fetches the url of the filename looking for...
private URL getURL(String filename)
{
URL url=null;
try{
url=this.getClass().getResource(filename);
}
catch(Exception e) {}
return url;
}
AffineTransform id=new AffineTransform();
Code for paint component...
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d=(Graphics2D)g;
AffineTransform trans=new AffineTransform();
Random rand=new Random();
g2d.setColor(Color.BLACK);
width=getSize().width;
height=getSize().height;
g2d.fillRect(0,0,width,height);
Loop for generating random ships on screen
for(int s=0;s<20;s++)
{
trans.setTransform(id);
trans.translate(rand.nextInt()%width,rand.nextInt()%height);
trans.rotate(Math.toRadians(360*rand.nextDouble()));
double scaled=rand.nextDouble()+1;
trans.scale(scaled,scaled);
trans.drawImage(img,trans,this);
}
}
}
1)Instead of using paint(Graphics g) for custom paintings you need to use paintComponent(Graphics arg0) of JComponent. For example draw image on JPanel and the add panel to your frame. Your JFrame isn't a JComponent.
2) As I know public static void main(String[] args) ;)
Read more about customPaintings.
The best way to add image in JFrame is to use JLabel.
Example:
JLabel image = new JLabel(new ImageIcon("Image.jpg"));
Now add this JLabel(image) into your JFrame.
public RandomImages()
{
super("Random Images");
setSize(450,450);
setVisible(true);
setLayout(new FlowLayout());//you have not used the Layout
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel image = new JLabel(new ImageIcon("Image.jpg"));
add(image);
}
Another way is to use drawImage() function of Graphics class in paint(Graphics g) function .
But you should use paintComponent against paint
I'm studying java currently, and yet again I ran into a code in the book which doesn't wanna work and i can't figure out why. This code snippet is from Head First Java
import javax.swing.*;
import java.awt.*;
public class SimpleGui {
public static void main (String[] args){
JFrame frame = new JFrame();
DrawPanel button = new DrawPanel();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
}
}
import java.awt.*;
import java.lang.*;
public class DrawPanel extends JPanel {
private Image image;
public DrawPanel(){
image = new ImageIcon("cat2.jpg").getImage();
}
public void paintComponent(Graphics g){
g.drawImage(image,3,4,this);
}
}
the image is in the same directory where my class files are, and the image is not showing. What am i missing here?
1) In your paintComponent() you must to call super.paintComponent(g);. Read more about custom paintings.
2) instead of Image use BufferedImage, because Image its abstrat wrapper.
3)use ImageIO instead of creating Image like this new ImageIcon("cat2.jpg").getImage();
4)Use URL for resources inside your project.
I changed your code and it helps you:
class DrawPanel extends JPanel {
private BufferedImage image;
public DrawPanel() {
URL resource = getClass().getResource("cat2.jpg");
try {
image = ImageIO.read(resource);
} catch (IOException e) {
e.printStackTrace();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 3, 4, this);
}
}
I was trying to load a few images using java but it seems to be extremely slow, it's around 13 images I'm trying to get each of 9KB size.
Is it my code or is it java that's causing the problem. I can load all the images alot faster using the browser.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageSample {
static public void main(String args[]) throws Exception {
JFrame frame = new JFrame("Display image");
//Image url here
String url="";
JPanel panel = new testImage();
frame.add(panel);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
}
}
class testImage extends JPanel {
static Image image;
public void testImage(String url)
{
image = Resources.getImage(url);
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, 40, 40, null);
}
}
class Resources
{
private static Resources myResource = new Resources();
// NOTE: there is no error checking here so if parameter is mistyped
// somewhere else in code, then this will probably throw a nullpointerexception
public static Image getImage(String name)
{
// TODO: Find out which way is better or preferred
URL url=null;
try {
url = new URL(name);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Toolkit.getDefaultToolkit().getImage(url);
}
}
Thanks,
Sreejith
Your program isn't actually doing what you think it's doing because you have made some fundamental mistakes with your class and method names:
class testImage extends JPanel {
static Image image;
public void testImage(String url)
{
image = Resources.getImage(url);
}
public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, 40, 40, null);
}
}
The standard is that class names should always begin with an upper-case letter, and method names should begin with a lower-case letter to avoid confusion. Because you have confused the two, you didn't notice that the testImage(url) you declare in this class is a void method, not a constructor, even though the name is the same. Therefore, when you call JPanel panel = new testImage(); you are not calling that method - you're just calling the default empty constructor that every class is given if no constructors are declared in the code. Note also that you haven't used the variable url and that your field image should not be static.
To be honest, you're going about the whole thing the wrong way and should start again from scratch. Costis' solution looks good. You should definitely give ImageIcons a try because they remove the hard work of having to manually get the resource URL and render it.
Try this example with your image. It is not slow.
public class ImageLoad extends JFrame {
public ImageLoad() {
setSize(800, 800);
JPanel panel = new JPanel();
ImageIcon icon = new ImageIcon("singer.jpg");
JLabel label = new JLabel();
label.setIcon(icon);
panel.add(label);
add(panel);
}
public static void main(String[] args) {
new ImageLoad().setVisible(true);
}
}