Matisse properly setting image to panel - java

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

Related

After buiding java app, some GUI components does not work properly, but during IDE tests everything is fine. Why?

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 don't know why my image is not showing on the frame [duplicate]

This question already has answers here:
I took this code straight out of 'Java all in one for Dummies' ....why doesn't it work?
(2 answers)
Closed 8 years ago.
So, I do not know why my image is not showing because I put the image in the right folder and I believe that the code below is right. The result of this code is just a blank white frame background. I thought the image was corrupted but I tried a different image and its the same result. Anyway I will be highly grateful if anyone could solve this.
package fia_project;
import java.awt.Color;
java.awt.*;
import javax.swing.*;
public class Fia_test extends JFrame {
public Frame kenny;
public Fia_test(){
super("");
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setVisible(true);
setSize(350, 100);
Container pane = getContentPane();
getContentPane().setBackground(Color.WHITE);
ImageIcon icon = new ImageIcon("speaker.png");
JLabel label2 = new JLabel(icon);
add(label2);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Fia_test t = new Fia_test();
}
}
Use ImageIO.read instead of ImageIcon as it will generate an error if the image can not be loaded, much more useful for diagnostics. See Reading/Loading an Image
ImageIcon(String) expects that the specified String represents a file on the file system. From the looks of you code, it is possible that you've placed the image within the source directory of your code.
Assuming that the image has been bundled into the resulting Jar file, you will no longer be able to access the image as if it was a file on the file system, but will need to use Class#getResource to load it...
For example...
BufferedImage img = ImageIO.read(getClass().getResource("speaker.png"));
ImageIcon icon = new ImageIcon(img);
Assuming that speaker.png is in the same directory as the class file.

Loading an image from folder in project

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.

How to add icon into Java (NetBeans) from Mac Os X?

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

Loading an Image in an Applet without getImage()?

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

Categories

Resources