I've created GUI for my application using Netbeans' GUI Builder. I am trying to display a JFrame containing a JLabel with an image, and I can't get the Image to display.
My generated code :
private void initComponents() {
//...
jLabel1 = new JLabel(new ImageIcon(myPicture));
}
And my class code:
public class GUIWindow extends javax.swing.JFrame {
BufferedImage myPicture;
/** Creates new form GUIWindow */
public GUIWindow() throws IOException {
myPicture = ImageIO.read(new File("images/logo.png"));
initComponents();
this.add(jLabel1);
}
}
but I still don't see an image ... (path to the image file is fine) its sth like:
my-project :
/build
/dist
/images/logo.png
/nbproject
/src (here I have all my source files)
/build.xml
/manifest.mf
you can use like this
URL imgSmartURL = this.getClass().getResource("your image path");
jLabel1 = new JLabel(new ImageIcon(imgSmartURL), JLabel.CENTER);
I would do something like this instead.
JLabel dice1 = new JLabel();
ImageIcon one = new ImageIcon("dice/1.png");
//set dice1 position
dice1.setLocation(20, 100);
dice1.setSize(115, 115);
dice1.setIcon(one);
gamepanel.add(dice1);
If you are using netbeans you can directly add an image to a jLabel by setting properties. Right click on the jLabel -> properties -> icon -> (if it's external image) import to project(upload your image) -> ok .
It'l be added into your jLabel.
I'd suggest you copy the image in a seperate folder(images).
Then use Toolkit.getDefaultToolkit().getImage("images/A.png");
I believe there's a similar question
private ImageIcon imageIconPrint =
new ImageIcon(getClass().getResource("/image/print.gif"));
create button and add follwing code:
jbtCanada.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jlblFlag.setIcon(imageIconCanada);
}
});
this would help i think
Related
I am currently learning java and I have problem and can't find anything about it. I got an "javax.imageio.IIOException: Can't read input file!"
I don't understand what I did wrong :
this is my code :
public class FirstWindoww extends JFrame {
JTextField usernameText = new JTextField(30);
private JPanel panel1;
private JPanel panel2;
public FirstWindoww() {
super("FROGGER GAME");
JFrame frame = this;
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setSize(400, 400);
this.setLayout(new FlowLayout());
panel1 = (JPanel) this.getContentPane();
panel1.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
panel1.setLayout(new FlowLayout());
panel2 = (JPanel) this.getContentPane();
panel1.setBackground(Color.GREEN);
JPanel startingGame = new JPanel();
this.setVisible(true);
JLabel username = new JLabel("ENTER YOUR NAME");
panel1.add(username);
panel1.add(usernameText);
usernameText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bouton cliqué !");
}
});
JButton start = new JButton("START");
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.remove(panel1);
frame.add(panel2);
frame.validate();
}
});
panel1.add(start);
JButton exit = new JButton("EXIT");
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
panel1.add(exit);
JButton help = new JButton("HELP");
help.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
panel1.add(help);
try {
// Load the background image
BufferedImage img = ImageIO.read(new File("C:\\Users\\N\\Documents\\testGUI\\srce\\grenouille"));
this.setContentPane(new JLabel(new ImageIcon(img)));
} catch (IOException exp) {
exp.printStackTrace();
}
JLabel imageLabel = new JLabel();
imageLabel.setIcon(new ImageIcon("C:\\Users\\N\\Documents\\testGUI\\src\\grenouille.png"));
panel1.add(imageLabel);
}
Here are the error in a picture and you can see the fields on the right enter image description here
Thank you for taking the time to read this. Have a very good day everyone :) !!!
Are you sure you have the correct path as well?
BufferedImage img = ImageIO.read(new File("C:\\Users\\N\\Documents\\testGUI\\srce\\grenouille"));
And
imageLabel.setIcon(new ImageIcon("C:\\Users\\N\\Documents\\testGUI\\src\\grenouille.png"));
Don't use absolute paths, like C:\Users\N\Documents\testGUI\src\grenouille, these are going to cause you no end of issues if you move the location of the program/image.
Also, looking at you path, C:\Users\N\Documents\testGUI\srce\grenouille, you seem to have a typo in src (ie srce) and you're missing the file extension off grenouille
One tip when trying to deal with these issues is to check the result of File#exits, this will give you a quick indication of possibly incorrect path laterals.
Instead, you should be focused on using "embedded resources", this allows the resource to be bundled with the binaries and they become more easily accessible at runtime.
The exact methods for doing this will come down to the IDE you are using and the workflow you use to build and package the project.
For Ant based Netbeans projects (and I believe Eclipse as well), you can place the resource directly under the src folder of the project. The build system will then include it in the resulting Jar file when you export the project. For Maven based projects, it's a bit more involved and I'm not going to discuss it here.
So, once you have the resource "embedded", you can simply use Class#getResource (or Class#getResourceAsStream depending on your needs), for example...
BufferedImage img = ImageIO.read(getClass().getResource("/grenouille.png")));
The location of the resource is relative to the top/root of the class path, in to make it simpler, think off it as offset from the top of the src directory (excluding src)
If you continue to have issues, you're going to have to diagnose the problem at your end. Start by doing a clean/build (or export of the project) and unzip the resulting Jar file and check its contents. If the resource doesn't exist, either the project isn't configured properly or the resource is in the wrong location.
I am still very new to Java and programming in general. I am trying to display a GIF using Swing and the following code:
JPanel contentPane;
JLabel imageLabel = new JLabel();
public FrostyCanvas(String imageName) {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
contentPane = (JPanel) getContentPane();
contentPane.setLayout(new BorderLayout());
setSize(new Dimension(1600, 900));
setTitle("FrostySpirit v1.1.1 (Beta) - FrostyCanvas");
// add the image label
ImageIcon ii = new ImageIcon(this.getClass().getResource(imageName));
imageLabel.setIcon(ii);
contentPane.add(imageLabel, java.awt.BorderLayout.CENTER);
// display target GIF
this.setLocationRelativeTo(null);
this.setVisible(true);
} catch (Exception exception) {
exception.printStackTrace();
}
}
The method call is the following: (in a different class)
FrostyCanvas FC = new FrostyCanvas("old.gif");
The GIF is animated at this point. I then try to replace the GIF with another one using the following method: (in the same class as ForstyCanvas(String imageName))
public void changeGif(String imageName) throws IOException
{
Icon icon; File file;
file = new File(imageName);
icon = new ImageIcon(ImageIO.read(file));
imageLabel.setIcon(icon);
}
I call the method above in a different class using the following code:
FC.changeGif("D:\\new.gif")
The image is successfully replaced. However, now it only shows the very first frame of new.gif and is no longer animated. How can I make the new GIF move?
The way ImageIO reads the image is creating a static image. The thing to do is to use ImageIcon's loader.
ImageIcon replacement = new ImageIcon(file.toURI().toURL());
That way you are using the same method to construct the image icon as you do with the resource / url.
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).
I'm trying to get the Thumbnail that is associated to a particular file, and then resize it. I've been testing on Mac, and haven't been able to find a solution that would allow me to achieve this.
Code so far:
import com.apple.laf.AquaIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class TestSystemIcon extends JFrame
{
JPanel panel;
ImageIcon icon;
public TestSystemIcon()
{
panel = new JPanel();
JButton button = new JButton("Open...");
final JLabel label = new JLabel();
icon = null;
final JPanel en = new JPanel(new FlowLayout(FlowLayout.CENTER));
label.setHorizontalAlignment(SwingConstants.CENTER);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null) == JFileChooser.OPEN_DIALOG)
{
File file = fileChooser.getSelectedFile();
icon = resizeIcon(getThumbnail1(file),200,200);
// icon = resizeIcon(getThumbnail2(file),200,200);
System.out.println(icon);
label.setIcon(icon);
en.add(label);
revalidate();
repaint();
}
}
});
panel.add(button);
this.add(panel,BorderLayout.NORTH);
this.add(en,BorderLayout.CENTER);
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public ImageIcon getThumbnail1(File file)
{
JFileChooser f = new JFileChooser();
Icon i = f.getIcon(file);
//Mac Conversion.
Image image = AquaIcon.getImageForIcon(i);
return new ImageIcon(image);
}
public ImageIcon getThumbnail2(File file)
{
return new ImageIcon(file.getPath());
}
public ImageIcon resizeIcon(ImageIcon imageIcon,int width, int height)
{
return new ImageIcon(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
public static void main(String[] args)
{
TestSystemIcon test = new TestSystemIcon();
test.setVisible(true);
}
}
Version1 of getting the thumbnail has following behaviour:
Can open thumbnails
Very small, scaling not suitable.
Version2 of getting thumbnail has following behaviour:
Doesn't display image, despite finding image (System.out proves this).
Except for pdf, where instead it displays the actual file, as opposed to the
thumbnail
When it does work i.e. pdf, it scales nicely.
I know I can use sun.awt.shell.ShellFolder;, however I am aiming for a cross-platform solution.
Thanks for any help
I looked at some code that I have done in the past and seems this works fine when you use JLabel with and ImageIcon, try this code that resized a large image to 100x100,
ImageIcon icon = new ImageIcon("Penguins.jpg");
Image img = icon.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
// if the file is not an image, but a file on the system,
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
Image img = ((ImageIcon) icon).getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon1 = new ImageIcon(img);
JLabel image = new JLabel(icon1);
I dont know why I cant add image to my JPanel
i use code:
class PanelGlowny extends JPanel {
private JLabel adam;
private JButton henryk;
PanelGlowny(){
this.setLayout(new BorderLayout());
ImageIcon imageurl = new ImageIcon("logo.jpg");
//Image img = imageurl.getImage();
adam = new JLabel(imageurl);
add(adam, BorderLayout.NORTH);
henryk = new JButton();
add(henryk, BorderLayout.CENTER);
}
}
Image is in the same folder as class, but if I use url to image it also do not add anything.
This code adding button, but do not add image :(
The problem is probably with my JDE, or Sandbox or sth like this, because code should be fine.
Try this:
imageurl = new ImageIcon(getClass().getResource("logo.jpg"));
Check How to Use Icons tutorial.
EDIT: loading remote image
Try that to load your image from web:
public static void main(String args[]) {
try {
JOptionPane.showMessageDialog(null, "", "",
JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(new URL("http://marinerczarter.pl/wp-content/themes/twentyten/images/headers/path.jpg")));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "Failure", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}