static fields getResource - java

everybody.
I am novice in Java and making training project with UI.
In process of trainings I decided to load icons from resources and to move its loading in the different class.
And got problem.
I really tried to find answers by myself but could not.Code bellow.
Main class
package scv.paul;
…
/**
* Create the application.
*/
public TestApp() {
Logger.getLogger(loggerName).fine("Showing main window");
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("Test App");
**frame.setIconImage( MyImages.appIcn.getImage());**//here try to load icon
And get exception:
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
Utility class
package scv.paul;*
import javax.swing.ImageIcon;
public class MyImages {
public static final ImageIcon appIcn = new ImageIcon ( MyImages.class.getResource ( "AppIcon.png" ) );
public static final ImageIcon BtnIcn = new ImageIcon ( MyImages.class.getResource ( "OK.png" ) );
public static final ImageIcon exitIcn = new ImageIcon ( MyImages.class.getResource ( "door.png" ) );
}
Images lay in "\bin" folder
I understand that the problem in the initialization of the static fields. But can’t understand reason.
I got this error if I call even such static field
public static final String imgPath = System.getProperties().getProperty("user.dir")+"\\img\\";
But I have no errors if I call in main class this static field
public static final String imgPath = "c://myProjectPath//bin";
And I could not find how to work with resources in good stile. Where I could read it?

Don't use static variables for something like this. There is no need to keep a reference to the icon. Just read the Icon and add it to your button.
Just load the images in the constructor of your class (when you create your buttons). See the section from the Swing tutorial on How to Use Icons for more information and working examples.
The tutorial will also show you how to better structure your code so the Swing components are created on the Event Dispatch Thread.
Keep a link to the tutorial handy for other Swing basics.

Put you images in the directory of the projecet, e.g. where the bin and src folders are located.
Its best to use a static method to read in files aswell incase they fail. Say you your resource folder within the directory called resources, your code would look something like this.
public static ImageIcon makeImageIcon(String filename) {
BufferedImage myPicture = null;
try {
myPicture = ImageIO.read(new File("resources/" + filename));
} catch (IOException e) {
e.printStackTrace();
}
return new ImageIcon(myPicture);
}
And then call this with the file name you want the same way you have done above.
public static ImageIcon image= makeImageIcon("myImage.png");
Hope this helps.

Related

Netbeans Platform: how to use a Frame instead of a TopComponent?

In my project (with the Netbeans Platform and JavaFX), which is composed by several Tabs (all of them are created subclassing the TopComponent class) I'm trying to implement another tab, which should show the screen of a Virtual Machine already running on VirtualBox.
The problem is that the tool I'm using is composed by a Frame (from Java awt) as top-level container and, naturally, if I try to add it inside my top component I get an exception because it's not possible to include a top-level container inside another top-level container.
So, this is my question: is it possible to create a new component with the NetBeans Platform without using the TopComponent class? I already tried to do that, but the new tab doesn't appear.
#TopComponent.Description(preferredID = "MyTopComponent",
// iconBase="SET/PATH/TO/ICON/HERE",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
#TopComponent.Registration(mode = "editor", openAtStartup = true)
#ActionReference(path = "Menu/Window" /* , position = 333 */ )
#TopComponent.OpenActionRegistration(displayName = "#CTL_MyAction", preferredID = "MyTopComponent")
public class MyTopComponent extends TopComponent {
/**
* Logging Facility Instance
*/
private static final Logger LOG = LoggerFactory.getLogger(MyTopComponent.class);
private JFXPanel fxPanel;
private RDPClient rdpClient;
private Frame rdpFrame;
public MyTopComponent() {
initTopComponent();
initFXComponent();
setClientProperties();
}
#Override
public void componentClosed() {
// TODO add custom code on component closing
}
private void initTopComponent() {
setName(Bundle.CTL_MyTopComponent());
setToolTipText(Bundle.HINT_MyTopComponent());
}
private void setClientProperties() {
putClientProperty(TopComponent.PROP_CLOSING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_DRAGGING_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_UNDOCKING_DISABLED, Boolean.TRUE);
}
private void initFXComponent() {
try {
rdpClient = new RDPClient();
} catch (RdesktopException ex) {
Exceptions.printStackTrace(ex);
}
setLayout(new BorderLayout());
fxPanel = new JFXPanel();
rdpFrame = rdpClient.getComponent();
// fxPanel.add(rdpClient.getComponent());
add(fxPanel, BorderLayout.CENTER);
Platform.setImplicitExit(false);
}
If I try to add the frame inside the JFXPanel it raises an exception. The same happens if I try to add it directly inside the container. Any suggestions?
A Frame, by definition, is a top-level window component. Frames cannot be placed inside another component, other components are placed inside Frames.
If the tool only provides a Frame, it will necessarily be its own window. The only thing you can do with it is set its location, dimensions, show it and hide it, set the title, other framey stuff.

Cannot display image with correct path using ImageIcon

I've been having an issue with displaying images in Java with the ImageIcon class. The code is very simple, but it simply displays a window like
.
import javax.swing.*;
public class TestButtonIcons {
public static void main(String[] args) {
ImageIcon usFlag = new ImageIcon("images/usFlag.png");
JFrame frame = new JFrame();
JButton jbt = new JButton(usFlag);
frame.add(jbt);
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
My image is located under the src folder, and my IDE can also detect it, since it shows
.
Also, if I change the path mentioned above into the full path, like
"/Users/Mac/Documents/Java TB/ImageIcons/src/images/usFlag.png"
The program works normally.
Any help will be appreciated.
Thanks!
ImageIcon(String) assumes that the image is located on the disk somewhere. When you place the image inside the src directory, most IDE's will bundle the image into the resulting Jar (AKA embedded resource), which means that they are no longer a "file" on the disk, but a byte stream in a zip file, so you need to access them differently.
Start by using ImageIO.read, unlike ImageIcon, it will throw an IOException when the image can't be loaded.
You need to use Class#getResource or Class#getResourceAsStream depending on how need to reference it, for example...
BufferedImage image = null;
try {
image = ImageIO.read(getClass().getResource("/images/usFlag.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
Take a look at Reading/Loading an Image for more details
Make sure you use "./path" or else it might think it's an absolute path. "." is the current directory, which indicates a relative path instead of an absolute one.
Problem is in the location of the image. Place your image in source folder. Try like
JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("images/usFlag.png"));
button.setIcon(new ImageIcon(img));
} catch (IOException ex) {
}
I assume that the image is in src/images.
The path you give to the constructor of ImageIcon is relative to the location of your class.
So if your class is org.example.TestButtonIcons it will look for org/example/images/usFlag.png
Hope this helps.

My method from another class is not being called?

Alright I am super confused right now, I am using a piece of code in my program that is 95% similar to another piece I've used in an another program, the only difference is that it worked in the previous program...
it is basically a Image loading class/method and I'm trying to call it in my main class but its not working and the "cannot find symbol - class Image" error occurs.
Where I'm calling the method from my GameImage class:
//STORE IMAGES
private static Image background;
GameImage class:
public class GameImage
{
public static Image loadImage(String imagePathName) {
// All images are loades as "icons"
ImageIcon i = null;
// Try to load the image
File f = new File(imagePathName);
if(f.exists()) { // Success. Assign the image to the "icon"
i = new ImageIcon(imagePathName);
}
else { // Oops! Something is wrong.
System.out.println("\nCould not find this image: "+imagePathName+"\nAre file name and/or path to the file correct?");
System.exit(0);
}
// Done. Either return the image or "null"
return i.getImage();
} // End of loadImages method
}
Where I load the image in main class:
//load the images
background = GameImage.loadImage("Images//background.jpg");
So yeah I dont know why that error keeps popping up because ive used that exact same code structure and GameImage class in another program... hmm
Any help would be great thanks :)
You lack the Image import statement.
Import the Image class and you should be fine.

How can I use the return statement from one method in another?

I want to call the return statement tempimage in load_picture by passing it to showWindow, but I'm not sure how. heres a snippet of my code. edit:
i guess what I'm trying to say is, I'm not exactly sure what to do with the hardcoded "picture1.gif". I understand that I need to call a method to load the image, but I'm not too sure what to put in place of it.
:
package project3;
import java.util.Scanner;
import javax.swing.;
import java.awt.;
import java.net.*;
public class Project3 {
//initializing global
static Project3 theobject = new Project3();
final static int MIN_NUMBER=1;
final static int MAX_NUMBER=8;
static int image_number=1;
static Image theimage;
// This routine will load an image into memory, non-static requires an object
// It expects the name of the image file name and a JFrame passed to it
// It will assume an Internet conection is available
// It can only be called AFTER the program object has been created
// It will return a type Image variable, call it like this: theimage = object.load_picture("picture1.gif", frame);
// (hard code 'picture1.gif' only when testing - USE a method or variable for 'real' call)
// This code requires you to do an 'import java.awt.*' and an 'import java.net.*'
// Note: this method is using parameter and return type for input/output
// This routine will load an image into memory, non-static requires an object
// It expects the name of the image file name and a JFrame passed to it
// It will assume an Internet conection is available
// It can only be called AFTER the program object has been created
// It will return a type Image variable, call it like this: theimage = object.load_picture("picture1.gif", frame);
// (hard code 'picture1.gif' only when testing - USE a method or variable for 'real' call)
// This code requires you to do an 'import java.awt.*' and an 'import java.net.*'
// Note: this method is using parameter and return type for input/output
public Image load_picture(String imagefile, JFrame theframe)
{
Image tempimage;
// Create a MediaTracker to inform us when the image has
// been completely loaded.
MediaTracker tracker;
tracker = new MediaTracker(theframe);
// getImage() returns immediately. The image is not
// actually loaded until it is first used. We use a
// MediaTracker to make sure the image is loaded
// before we try to display it.
String startURL;
if (imagefile.startsWith("http"))
startURL = "";
else
startURL = "http://www.canyons.edu/departments/comp_sci/ferguson/cs111/images/";
URL myURL=null;
try
{
myURL = new URL(startURL + imagefile);
}
catch(MalformedURLException e) {
System.out.println("Error caught " + e.toString());
}
//tempimage = getImage(myURL); // JApplet version
tempimage = Toolkit.getDefaultToolkit().getImage(myURL); // stand alone program version
// Add the image to the MediaTracker so that we can wait for it
tracker.addImage(tempimage, 0);
try { tracker.waitForID(0); }
catch ( InterruptedException err) { System.err.println(err); }
return tempimage;
}
// This class/method uses a global variable that MUST be set before calling/using
// note: You can not call the paint routine directly, it is called when frame/window is shown
// look up the repaint() routine in the book
// Review Listings 8.5 and 8.6
//
public static class MyPanel extends JPanel {
public void paintComponent (Graphics g) {
JPanel panel= new JPanel();
int xpos,ypos;
super.paintComponent(g);
// set the xpos and ypos before you display the image
xpos = 300; // you pick the position
ypos = 200; // you pick the position
if (theimage != null) {
g.drawImage(theimage,xpos,ypos,this);
// note: theimage global variable must be set BEFORE paint is called
}
}
}
public static void showWindow( String filename ) {
// create, size and show a GUI window frame, you may need to click on taskbar to see window
//display the filename in the title of the window frame, otherwise the window will be blank (for now)
JFrame frame1= new JFrame();
theimage = theobject.load_picture("picture1.gif", frame1);
//"picture1.gif" is hardcoded, I want to call this using a method
frame1.setTitle(filename);
frame1.setSize(440,302);
frame1.setLocation(400,302);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
}
Any help is appreciated. Thanks
The value that is returned by the load_picture method can be sent directly to the showWindow method, or you can assign it to a variable:
String filename = "your/filename";
JFrame theFrame = new JFrame();
Project3 project = new Project3();
MyPanel.showWindow(project.load_picture(filename, theFrame);
From within the showWindow method, just call the load_picture method as follows:
Image tempImage = load_picture(filename, frame1);
From here you can do anything you like with the tempImage object.

Problem in adding Icon to a JFrame

I have tried several methods to add an Icon to a JFrame. Every method work perfectly when I run it using the source code.
for example:
jframe.setIconImage(Toolkit.getDefaultToolkit().getImage("iconimages/icon.png"));
But none of them work when I run it using the jar file. I know the problem is with the path of the image file. How can I solve this?
Edit:
public Ui() {
initComponents();
setLocationRelativeTo(null);
this.setIconImage(getImageIcon("icon.png").getImage());
}
private ImageIcon getImageIcon(String fileName) {
String imageDirectory = "iconimages/";
imgURL = getClass().getResource(imageDirectory + fileName);
return new ImageIcon(imgURL);
}
I tried this but now I get a null pointer exception.
--------------------------------------------------------------------------------
Edit [Solution] : I found the solution.
I added ../ to the path additionally and it works perfectly!!! :D
ImageIcon imageIcon = new ImageIcon("../imageicons/icon.png");
this.setIconImage(imageIcon.getImage());
Thanks all for try to help me. :)
You should use a URL. Like this:
/**
* Loads and returns an {#link Image} resource.
* #param fileName name of the image resource.
* #return Image as resource.
*/
public Image getResourceImage(String fileName) {
String imageDirectory = "images/";
URL imgURL = getClass().getResource(imageDirectory + fileName);
Image image = null;
try {
image = ImageIO.read(imgURL);
} catch (IOException e) {}
return image;
}

Categories

Resources