I am currently working on a text-based RPG with a GUI and I can't seem to get the image I want to use to load.
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel(String location)
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage(location);
}
public void paintComponent(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
img.setAccelerationPriority(SCALE_FAST);
}
}
This is the code I use for the panel itself. I tried putting the image file in the root directory of my project but it doesn't seem to help. I have created a folder within the project which I intend to use for all of my images.
I'm not sure what the issue is here. I know I tried using paint() instead of paintComponent(), but then the buttons and other components won't draw until you mouse over them, for some reason.
Any ideas?
I have already posted it at below links in the same context. Please have a look:
ImageIcon does not work with me
How to retrieve image from project folder?
Read image from another directory
It's already described in Oracle Java Tutorial on Loading Images Using getResource
Note: Don't forget to call super.paintComponent() in the overridden paintComponent() method.
Related
Here's a simple question: how to get the source of an image. The following are the codes of subclass:
import javax.swing.JComponent;
import java.awt.*;
public class PuzzleGameBoard extends JComponent {
private Image penguin;
public PuzzleGameBoard() {
penguin = ;
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(penguin, 30, 30, this);
}
}
I have problem printscreening my java program and my files to be uploaded due to technique limitation. But can anybody teach me the best way of getting the source of an image? Sorry to be not quite specific again..
It's worth reading Java Tutorial on Loading Images Using getResource
Just put all the images inside the project itself or bundle all the required resources in a jar and add it in the class-path, then try any one based on image location.
// Read from same package
ImageIO.read(getClass().getResourceAsStream("c.png"));
// Read from images folder parallel to src in your project
ImageIO.read(new File("images/c.jpg"));
// Read from src/images folder
ImageIO.read(getClass().getResource("/images/c.png"))
// Read from src/images folder
ImageIO.read(getClass().getResourceAsStream("/images/c.png"))
Read more...
Note: Call super.paintComponent(g); at first line in the overridden paintComponent() method.
I got a problem with NetBeans resource managing while setting images to pannel:
This is my not working code:
try {
BufferedImage myPicture = ImageIO.read(new File("images/3D.jpg"));
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
pnlMain.add(picLabel); //the main and only pannel made by matisse is called pnlMain
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Cannot set image");
}
The folder called "images" is in the MAIN project folder. There are several folders: build, nbproject, src and "images".
The problem I have is that the program runs but it doesnt set the image...
Someone suggested me to make another class in different package with this code:
public class PanelImage extends JPanel{
private Image imag;
public PanelImage(Image img){
if(imagen != null){
this.imagen = img;
}
}
#Override
public void paint(Graphics g){
g.drawImage(img, 0,0, getWidth(), getHeight(), this);
setOpaque(false);
super.paint(g);
}
}
But i cant find a proper way of implementing it...
For your ImagePanel class
super.paint[Component] before all the other stuff.
Don't override paint but instead paintComponent
Don't set properties in paintComponent method ie setOpaque(). Beside, JPanel is opaque by default
Override getPreferredSize() for painting on panels
For loadng images
Make a habit of not reading images from the file system, unless the application is specific to only your machine.
Instead read from the class path and make the image a resource by packaging it into the class path
Change your file structure
ProjectRoot
src
images
3D.jpg
Read from class path. Use ImageIO to make sure your path is correct. If it's invalid, an exception will be thrown
URL url = getClass().getResource("/images/3D.jpg");
Image image = ImageIO.read(url);
For Netbeans GUI Builder
You can set the label icon using the design tool
Select your label from the navigator or the design view.
Go to the properties window in the right and find the property icon
click the ellipses button to the right of the property and a dialog will appear.
Find your image and select OK (make sure your image is in a package in the src)
See related and maybe related
So I'm trying to add an icon into my program, but the textbook I'm reading explain how to only for Windows users. I would like to know how to add the icon. I have it on my program source folder and the code I have so far is something like this:
logo = new ImageIcon("~://resources//CherryBoom.png");
labelone = new JLabel("Fruit No.1 : ", logo, SwingConstants.LEFT);
JPanel panelone = new JPanel();
panelone.add(labelone, logo);
The icon still won't show on the windows panel, so I'm really lost here, and I don't know how can I get it to show into my program.
First of all, check the obvious solutions such as:
Have you done window.add(panelone);
Is the file in the correct spot/url is correct
Secondly, if you hate LayoutManagers like me, but still want to use javax.swing, you might try using drawString and drawImage methods in your panel's paintComponent(Graphics g) class. In detail:
You'll need to make your own JPanel:
public class MyPanel extends JPanel {
as well as override the method:
#Override
public void paintComponent(Graphics g) {
within the method, call this so the window can refresh itself and do other housekeeping things:
super.paintComponent(g);
then, use drawString and drawImage to draw these images in the place you would like them:
g.drawString("Fruit No. 1", x, y);
logo.paintIcon(this, g, x, y);
Whenever you change or draw an image, you'll also want to call in the main method:
panelone.repaint();
Hope this helps!
Java doesn't support expanding the "~" path directive.
Try this...
try {
File file = new File("~");
System.out.println(file.getAbsolutePath());
System.out.println(file.getCanonicalPath());
} catch (IOException exp) {
exp.printStackTrace();
}
I think you will find that it doesn't point to the users home folder.
Instead, you should be using System.getProperty("user.home")
logo = new ImageIcon(System.getProperty("user.home") + File.separator + "/resources/CherryBoom.png");
Now, having said that, I would strongly encourage you to use ImageIO over ImageIcon as you will get better feedback when something goes wrong.
Check out Reading/Loading an Image
I usually load images in Applets using:
this.getImage( getCodeBase(), "myimage.png" );
or
myapplet.getImage( getCodeBase(), "myimage.png" );
But what if I want to load an image from another class which is not a child of Applet, neither does it have a member which refers to the Applet?
Say, I have a sprite class, in whose update method I want to load images for animation:
#Override
public void update(){
frame++;
if ( frame > 3 ) frame = 1;
/* the problem */
loadImage( getCodeBase(), "myimage_" + frame + ".png" );
}
Of course I could include Applet app as parameter, but the sprite's update method gets called in so many different parts of the code and in so many other classes, that it will extremely complicate stuff and make life difficult.
So is there a way I can load an image from a file in an applet without using the applet's getImage() method?
So is there a way I can load an image from a file in an applet without using the applet's getImage() method?
Image img = ImageIO.read(url);
When loading an image from a file in a non-applet class definition or in an application, you need the following statements:
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image1 = toolkit.getImage("fileName.ext");
I am trying to display a JPEG image and a moving dot on a Java applet which I am using on a web based application. However, when I run the applet it works fine, but when I display the applet from the JSP page, I get the moving dot but not the JPEG image.
Is there a specific folder where the JPEG needs to be?
These are the 2 methods i use for drawing the picture and the moving dot on the screen.
public class mapplet extends Applet implements Runnable {
int x_pos = 10;
int y_pos = 100;
int radius = 20;
Image img, img2;
Graphics gr;
URL base;
MediaTracker m;
#Override
public void init() {
mt = new MediaTracker(this);
try {
//getDocumentbase gets the applet path.
base = getCodeBase();
img = getImage(base, "picture.jpg");
m.addImage(img, 1);
m.waitForAll();
} catch (InterruptedException ex) {
Logger.getLogger(movement.class.getName()).log(Level.SEVERE, null, ex);
}
public void paint (Graphics g) {
g.drawImage(img, 0, 0, this);
// set color
g.setColor (Color.red);
// paint a filled colored circle
g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
}
The code one below is the call from the jsp page
<applet archive="mapplet.jar" code="myapplets/mapplet.class" width=350 height=200>
</applet>
The jar file and the picture are in the same folder as the jsp page, and there is also a folder containing the contents of the class and image of the applet in the web section of the application. The applet loads fine however the picture doesn't display. I think it's not the code but the location of the picture that is causing a problem.
Thanks
Yes, the image should be in the same folder as the source code. I would recommend to do a folder called images and inside it put all your images and just change "picture.jpg" to "\images\picture.jpg". Check your website directory to see if the image is in the same folder as the source code.
Some comments that might make it more clear for you.
//getDocumentbase gets the applet path.
No. getDocumentBase() provides the path to the web page. But that is neither here, nor there, since this applet actually calls..
base = getCodeBase();
..which provides the codebase. The codebase defaults to the directory of the web page, unless a codebase parameter is specified in the applet element. Since the applet element declares no codebase, the base will be the same URL as the document base.
BTW: In the applet element
code="myapplets/mapplet.class"
..should be..
code="myapplets.mapplet"
And since common nomenclature for Java class names is EachWordUpperCase, the class name should be changed.
Doe the applet declare?
package myapplets;
BTW (2):
there is also a folder containing the contents of the class and image of the applet in the web section of the application.
What does that mean? Please provide complete paths from the root of the server to all resources (e.g. the HTML/JSP, Jar file & image) used.
please check your path ..or to resolve it please put your files inside a folder and pack it with JAR file.and provide the relative path of image files inside your jar.
Like:
let your applet name is myapp.class in package demoapp
then put your files in dir "images" inside demoapp and provide path relative to this path in all your java code.
dont forget to include image files in jar build.