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");
Related
I am working on GUI java project which contains FileChooser(combined with JLabel it becomes ImageChooser) and JTextArea (inside of JScrollPane). Both of these components are inside of JPanel.
When ever I ran it inside of IntelliJ Idea (version 2017.2.4)everything works fine:
UI when executed from IDE
But if I build Artifacts and create .jar file, then image inside of JLabel is not initialized and the size(height) of JTextArea becomes minimal(though minimal value is set to 200):
IU when executed from .jar file
I suspect that ImageIcon cannot be initialized due to relative path I provide:
...
imagePath = "src/main/resources/" + item.getImageName();
//item.getImageName() returns a proper image name, tested with
//System.out.println() and there is a proper image in that folder.
ImageIcon img = new ImageIcon(imagePath);
img = ImageManager.resize(img);
...
//Resize function in ImageManager class
public static ImageIcon resize(ImageIcon imageIcon, int size){
return resize(imageIcon, size, size);
}
public static ImageIcon resize(ImageIcon icon){
return resize(icon, defaultSize);
}
However, I've tried options with relative path like main/resources/ and /main/resources/ , but none of them worked both in IDE and .jar executable.
Is it a problem with a path?
If yes, why does it affect JTextArea's size?
P.S.
JTextArea's size becomes normal if there is an image in JLabel.
You are right, the way you fetch resources is problematic in a jar.
The way you should access them:
ImageIcon img = new ImageIcon(this.getClass().getClassLoader().getResource(item.getImageName()));
This method supports relative paths. Just make sure your src/main/resources directory is properly marked as a 'Resource Root' in IntelliJ IDEA.
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.
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
I am building a web application, in Java, where i want the whole screenshot of the webpage, if i give the URL of the webpage as input.
The basic idea i have is to capture the display buffer of the rendering component..I have no idea of how to do it..
plz help..
There's a little trick I used for this app:
count down demo app http://img580.imageshack.us/img580/742/capturadepantalla201004wd.png
Java application featuring blog.stackoverflow.com page ( click on image to see the demo video )
The problem is you need to have a machine devoted to this.
So, the trick is quite easy.
Create an application that takes as
argument the URL you want to fetch.
Then open it with Desktop.open( url
) that will trigger the current
webbrowser.
And finally take the screenshot with
java.awt.Robot and save it to diks.
Something like:
class WebScreenShot {
public static void main( String [] args ) {
Desktop.getDesktop().open( args[0] );
Robot robot = new Robot();
Image image = robot.createScreenCapture( getScreenResolutionSize() );
saveToDisk( image );
}
}
This solution is far from perfect, because it needs the whole OS, but if you can have a VM devoted to this app, you can craw the web and take screenshots of it quite easy.
The problem of having this app as a non-intrusive app is that up to this date, there is not a good html engine renderer for Java.
For a pure-java solution that can scale to support concurrent rendering, you could use a java HTML4/CSS2 browser, such as Cobra, that provides a Swing component for the GUI. When you instantiate this component, you can call it's paint(Graphics g) method to draw itself into an off-screen image
E.g.
Component c = ...; // the browser component
BufferedImage bi = new BufferedImage(c.getWidth(), c.getHeight(), TYPE_INT_RGB)
Graphics2d g = bi.createGraphics();
c.paint(g);
You can then use the java image API to save this as a JPG.
JPEGImageEncoder encoder = JPEGCodec.createEncoder(new FileOutputStream("screen.jpg"));
enncoder.encode(bi); // encode the buffered image
Java-based browsers typically pale in comparison with the established native browsers. However, as your goal is static images, and not an interactive browser, a java-based browser may be more than adequate in this regard.
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.