I am working on a Java Project. I have my images in my "resources" package and all my UI classes in my "UIPackage". I am using a JFrame form to design my window and put an image into a JLabel through the properties tab in the window editor. However, this does not scale the image so to get around this, I wrote code to grab an image from the resources package, scale it, and then display it in the JLabel. However, my attempts to grab an image file return null. The especially frustrating part is if I copy (not editing the generated code) what the form does when I add an image to the JLabel through the properties tab, it still doesn't work. What am I doing wrong here?
Project Navigator
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.io.IOException;
import java.awt.image.BufferedImage;
/**
*
* #author Admin
*/
public class LandingPage extends javax.swing.JFrame {
/**
* Creates new form LandingPage
*/
public LandingPage() {
initComponents();
//this works
sideArtLabel.setIcon(new ImageIcon(new ImageIcon("C:\\Users\\Admin\\Documents\\NetBeansProjects\\HowtoFeedYourDragon\\src\\main\\java\\resources\\2561-bearded-dragon-lawler.jpg").getImage().getScaledInstance(sideArtLabel.getWidth(), sideArtLabel.getHeight(),Image.SCALE_SMOOTH)));
//path is null
System.out.println("jpg 1 " + getClass().getResource("/resources/2561-bearded-dragon-lawler.jpg"));
//sideArtLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/2561-bearded-dragon-lawler.jpg")));
//but this doesn't. path is null
try
{
System.out.println("jpg 2 " + getClass().getResource("/resources/01.jpg"));
BufferedImage sideArtImg = ImageIO.read(getClass().getResource("/resources/01.jpg"));
ImageIcon sideArtIcon = new ImageIcon(sideArtImg);
sideArtLabel.setIcon(sideArtIcon);
}
catch(IOException e)
{
e.printStackTrace();
}
}
Related
I have tried many methods over the last few days with no success...I've trawled through various Stackoverflow entries and to no avail...I must be missing something.
I have tried across three different IDEs...IntelliJ, Eclispe and Netbeans.
The problem is when trying to turn my program into an executable jar it is unable to run (either by double clicking or running through command).
When executing the following on command:
java -jar D:\Computing\Programming\Java\Projects\JavaFXGameMenu\out\artifacts\JavaFXGameMenu_jar\JavaFXGameMenu.jar
I get: Error: Could not find or load main class root.Main
When i run the same but with javaw instead.. i get not error message, but nothing happens either.
I am predominately using IntelliJ as its a JavaFX application that I am building.
This is the project hierarchy:
When creating the Artifact I choose the following based upon other threads:
I then re run this using: Java -jar D:\Computing\Executables\JavaFXGameMenu.jar
I get the following issue:
I have put the relevant environment variables into my system and Path and I am using jre1.8.0_144.
Any help with tracking down what the problem could be is greatly appreciated
Code below...but this fully compiles and runs within IDE without errors...the problem is when its turned into a .jar and ran from command.
package root;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.effect.DropShadow;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.CycleMethod;
import javafx.scene.paint.LinearGradient;
import javafx.scene.paint.Stop;
import javafx.scene.shape.Line;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Screen;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main extends Application {
private double width = 1920;
private double height = 1080;
private Parent createContent(){
Pane root = new Pane();
root.setPrefSize(width, height); //W:860 H:600
ImageView imgLogo = null;
ImageView bottomlogo = null;
MenuItem newGame = new MenuItem("NEW GAME");
MenuItem continueGame = new MenuItem("CONTINUE");
MenuItem friends = new MenuItem("FRIENDS");
MenuItem settings = new MenuItem("SETTINGS");
MenuItem store = new MenuItem("STORE");
MenuItem exit = new MenuItem("EXIT");
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/dark.jpg"))) {
ImageView img = new ImageView(new Image(is));
img.setFitWidth(width);
img.setFitHeight(height);
root.getChildren().add(img);
} catch (IOException e){
System.out.println("Couldn't Load Image");
}
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/logo.png"))) {
imgLogo = new ImageView(new Image(is));
imgLogo.setX(1000);
imgLogo.setY(100);
imgLogo.setFitWidth(600);
imgLogo.setFitHeight(300);
} catch (IOException e){
System.out.println("Couldn't Load Image");
}
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/SteamAgony.png"))) {
bottomlogo = new ImageView(new Image(is));
bottomlogo.setX(100);
bottomlogo.setY(800);
bottomlogo.setFitHeight(200);
bottomlogo.setFitWidth(200);
bottomlogo.setOpacity(0.7);
} catch (IOException e){
System.out.println("Couldn't Load Image");
}
MenuBox menu = new MenuBox(
newGame,
continueGame,
friends,
settings,
store,
exit);
menu.setTranslateX(width / 3.4);
menu.setTranslateY(height / 2.5);
settings.setOnMouseClicked(event -> new SceneCreator().createScene(200,300));
exit.setOnMouseClicked( event -> Platform.exit());
root.getChildren().addAll(menu, imgLogo, bottomlogo);
return root;
}
#Override
public void start(Stage primaryStage) throws Exception{
Scene scene = new Scene(createContent());
primaryStage.setScene(scene);
primaryStage.initStyle(StageStyle.UNDECORATED);
primaryStage.show();
}
#Override
public void stop(){
//TODO
}
public static void main(String[] args) {
launch(args);
}
}
The error is at Main.createContent line 102. Maybe you forgot to initialize the child node (I'm not really familiar with JavaFX).
As #cedrikk mentioned, the problem is related to your code in Main.createContent.
You said the problem is when trying to run the jar as an executable -
did you try to run it within the IDE? If not - you should try to, and while at it - debug it to help you find the problem. Just right click your Main class and choose debug.
Regarding running it with javaw, the reason you got no error messages is because javaw executes java programs without a console - where you would normally get error messages unless using some logging solution.
You are adding a null element as a child of a Pane, causing the null pointer issue you are facing, if you use the debugger you'll be able to find where the variable that shouldn't be null is being set to null.
Edit - after code added
You are seeing 2 fields in try catches (imageLogo, bottomLogo), and adding them even if they fail, which adds nulls, causing the error.
You use a relative path for the images, this is probably the issue, are you running the jar from the project root? If not you could put the absolute path, but using resources would be more reliable, and allow the jar to run on different computers.
The problem was down to declaring inputStreams.
This works for both in IDE and running from jar:
String bgImg = "root/resources/dark.jpg";
URL bgImgPath = Main.class.getClassLoader().getResource(bgImg);
ImageView img = new ImageView(new Image(bgImgPath.toExternalForm()));
img.setFitWidth(width);
img.setFitHeight(height);
root.getChildren().add(img);
Compared to what I had before:
try(InputStream is = Files.newInputStream(Paths.get("src/resources/Images/dark.jpg"))){
ImageView img = new ImageView(new Image(is));
img.setFitWidth(width);
img.setFitHeight(height);
root.getChildren().add(img);
}catch (IOException e) {
System.out.println("Could not load");
}
The changes to the paths, were from where I tried adding the resource folder to the root folder instead of within src.
I've started Java a week ago, and now I would like to insert an image into my window.
Whatever I try I keep having this in Eclipse:
javax.imageio.IIOException: Can't read input file!
package graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import src.Common;
public class Window extends JFrame
{
public class Panel extends JPanel
{
public void paintComponent(Graphics g)
{
Image img;
try
{
img = ImageIO.read(new File("/logo.jpg"));
g.drawImage(img, 0, 0, this);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public Window(String title, int width, int height)
{
this.setTitle(title);
this.setSize(width, height);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(new Panel());
this.setVisible(true);
}
}
I think the code is pretty self-explaining.
I tried to solve the problem with this, this, and that .
What I'm trying to do is a desktop program, and my sources are stored like that :
training/src/graphics/Window
training/src/src/main
I did put the image I want to read in every folder, and still getting the issue :/
What did I do wrong?
EDIT Finally solved, here the answer
nIcE cOw gave me the link that helped.
So I did put my images into a folder, and change the way to access to them, as described in the link.
getClass().getResource("/images/yourImageName.extension");
Have you tried using new File("logo.jpg"); (without the leading /)?
And are you sure, the logo.jpg is copied to your output? (Some IDEs don't copy every file from your source-directories to your output (or target) directories.)
/src
|-> Window.java
|-> Logo.jpg
becomes
/out
|-> Window.class
(Note that the IDE/compiler does not copy the image to your output-directory and so the compiled code cannot find the image - allthough you did specify the correct path)
Try do debug which file resource you actually try to access. First step would be to get your new File("/logo.jpg").get [Canonical]Path() and print it to System.out (or alternatively watch in the the debugger). I guess the problem is the / before logo.jpg, which points to your root directory (e.g. c:) and your file isn't there, but I don't know your file setup in detail.
The problem is that you're looking at nothing before the image, so it's looking into a folder that isn't there to find it.
You have to create a folder to store the images in your project, and then call to it, your folder name in front of the image name. e.g.
ImageIO.read(new File("Folder/Image.png"));
Otherwise you can find the image by going through the entire directory, which isn't a good way as it takes longer, and when you move your project it won't be a working link as the directory will be different. For example:
ImageIO.read(new File("D:/eclipse/Workspace/Project/Folder/Image.png"));
Creating a folder in your project so its on the same level as the source folder in the directory and call to it for the image, like so:
Folder structure;
settings
src
Image Folder
bin
copypasting from a working project:
private JPanel getPanel() {
JPanel panel = new JPanel();
JLabel labelLcl = new JLabel("Ye ana!");
try {
File f = new File("./src/res/0.jpg");
//l.a(f.getCanonicalPath());
BufferedImage imgLcl = ImageIO.read(f);
ImageIcon iconLcl = new ImageIcon(imgLcl);
labelLcl.setIcon(iconLcl );
panel.add(labelLcl);
} catch (IOException e) {
e.printStackTrace();
}
return panel;
}
otherwise you can have folder/file read permission problem
I have been searching everywhere on how to set the icon image in Java, and it always ends up not working or it gives me errors. Here, in my main method is where I put the code:
public static void main(String[] args) {
Game game = new Game();
// This right here!
game.frame.setIconImage(new ImageIcon("/Icon.png").getImage());
game.frame.setResizable(false);
game.frame.setTitle(title);
game.frame.add(game);
game.frame.pack();
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
game.frame.setVisible(true);
}
My path for the image is "%PROJECT%/res/Image.png" and I just use /Image.png to go ahead and access my res folder (as I have done in other parts of my project) I have even converted it into an icon file, and tried that, but all it decides is to use the default Java icon.
Your problem is often due to looking in the wrong place for the image, or if your classes and images are in a jar file, then looking for files where files don't exist. I suggest that you use resources to get rid of the second problem.
e.g.,
// the path must be relative to your *class* files
String imagePath = "res/Image.png";
InputStream imgStream = Game.class.getResourceAsStream(imagePath );
BufferedImage myImg = ImageIO.read(imgStream);
// ImageIcon icon = new ImageIcon(myImg);
// use icon here
game.frame.setIconImage(myImg);
Use Default toolkit for this
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("Icon.png"));
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window family such as JFrame or JDialog:
IconImageUtilities.setIconImage(this);
The below method works well on Java 7 and above.
JFrame frame = new JFrame("MyAPP");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
frame.setIconImage(ImageIO.read(YourClass.class.getResourceAsStream("/icon.png")));
} catch (IOException ex) {
ex.printStackTrace();
}
frame.setVisible(true);
Park your icon.png image file to /src/main/resources.
I'm trying to create a splash screen using LWUIT. I want a form to load and display text and an imagefor 5 seconds then continue to the next form. I have a code but fails to show the image. The class and the image are stored together int he same package. Instead, it shows an error.
java.io.IOException
What could be the problem? This is the code
package tungPackage;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import javax.microedition.midlet.MIDlet;
public class photoMidlet extends MIDlet {
public void startApp() {
Display.init(this);
try {
Form splashscreen = new Form();
// Label splashText = new Label("Baldy");
Image image = Image.createImage("/splash.png");
Label pictureLabel = new Label(image);
splashscreen.addComponent(pictureLabel);
splashscreen.show();
} catch (Exception ex) {
Form x = new Form("ERROR");
String y = ex.toString();
Label g = new Label(y);
x.addComponent(g);
x.show();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Open your JAR file using a ZIP utility (e.g. 7-zip) and look in the root of the file. If splash.png isn't in the root of the jar that's your problem!
Place splash.png so it is in the root of the jar.
I am trying to read a static map from Google Maps on the following URL.
This works fine from my web browser, but when I try this from HtmlUnit I get an UnexpectedPage result. Does anyone know what this means?
According to the javadoc of UnexpectedPage, you're receiving an UnexpectedPage because server returns an unexpected content type. If you check the returned header in HtmlUnit you can see that it contains: Content-Type=image/png
Here's a little application that retrieves an image from an URL:
import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import com.gargoylesoftware.htmlunit.UnexpectedPage;
import com.gargoylesoftware.htmlunit.WebClient;
/** Small test application used to fetch a map. */
public class FetchMapSwingApp extends JFrame {
/** Serial Id. */
private static final long serialVersionUID = 1920071939468904323L;
/**
* Default constructor.
*/
public FetchMapSwingApp() {
// Make sure the application closes correctly
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
// The map where trying to read
String url = "http://maps.googleapis.com/maps/api/staticmap?center=55.690815,12.560678&zoom=15&size=400x500&sensor=false";
// Fetch the image
Image image = fetchMap(url);
// Add the image to the JFrame and resize the frame.
add(new JLabel(new ImageIcon(image)));
pack();
}
/**
* Fetch the image on the given URL.
*
* #param url
* the image location
* #return the fetched image
*/
private Image fetchMap(String url) {
Image image = null;
WebClient webClient = new WebClient();
webClient.setThrowExceptionOnScriptError(false);
try {
// The URL returns a png file!
UnexpectedPage page = webClient.getPage(url);
InputStream inputStream = page.getInputStream();
// Read the stream to an image
image = ImageIO.read(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
/**
* Start of the application.
*
* #param args
* the arguments to the main method
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new FetchMapSwingApp().setVisible(true);
}
});
}
}