How to pass a file location as a parameter as a string? - java

Currently I pass a hardcoded string file location to my object method which uses the string in the .getResources() method to load an image file. I am now trying to chooses an image using a load button and pass the loaded file location as a string into the getResource() method. I am using the filename.getAbsolutePath() method to retrieve the file location then passing the filename variable into the object method however this provides me with the following error -
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
The line of code that it points to having the error is the .getResources line where the image is loaded. I will post the code below to better understand my problem.
btnLoad.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File loadImage = fc.getSelectedFile();
String filename = loadImage.getAbsolutePath();
filename = filename.replaceAll("\\\\", "\\\\\\\\");
picLocation = filename;
ImageSwing imageSwing = new ImageSwing(filename);
System.out.println(filename);
}
}
The output of the file name is correct yet it still wont pass into the object.
public class ImageSwing extends JFrame
{
public JLabel label;
public ImageSwing(String S){
super("Card Stunt"); //Window Title
setLayout(new FlowLayout()); //lookup grid layout
Icon flag = new ImageIcon(getClass().getResource(S));
label = new JLabel(flag);
label.setToolTipText(S);
setSize(1350, 800);
//setMinimumSize(new Dimension(1200, 760));
}//main
}

It seems like you create an absolute filename with loadImage.getAbsolutePath(), but then you try to use this as a class path resource with new ImageIcon(getClass().getResource(S)).
Instead, you should just pass the absolute filename, as a string, to ImageIcon:
Icon flag = new ImageIcon(S);
Also, don't forget to add the label to the frame...
getContentPane().add(label);
Also, I'm not on Windows right now, but I don't think filename.replaceAll("\\\\", "\\\\\\\\"); is necessary.

Related

unable to get the path(url) of image with createIcon() method

So when i'm tried to put an icon to my button with createIcon() method that i declared inside of the button's class, it works fine.
BUT,
when i try to put the method in another class (say Utils.java), so that i don't need to re-declare the method in the class where the object needs icon, i get this message.
Unable to load image: /images/Save16.gif
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "java.net.URL.toExternalForm()" because "location" is null
*there's more message if needed
this is the button's class with createIcon() method inside
public class Toolbar extends JToolBar implements ActionListener{
private final JButton saveBtn;
public Toolbar() {
saveBtn = new JButton();
saveBtn.setIcon(createIcon("/images/Save16.gif"));
saveBtn.setToolTipText("Save");
saveBtn.addActionListener(this);
add(saveBtn);
}
private ImageIcon createIcon(String path) {
URL url = getClass().getResource(path);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
ImageIcon icon = new ImageIcon(url);
return icon;
}
}
this is the createIcon() method that i'm trying to declare in another class
public class Utils {
public static ImageIcon createIcon(String path) {
URL url = System.class.getResource(path);
if(url == null) {
System.err.println("Unable to load image: " + path);
}
ImageIcon icon = new ImageIcon(url);
return icon;
}
}
which changed the setIcon() method into:
saveBtn.setIcon(Utils.createIcon("/images/Save16.gif"));
from what i analyzed in the message the problem is might be the url which can't get the path from my button's class, i've tried several alternatives but it's still didn't work. how should i properly set this up? thanks
This works:
URL url = getClass().getResource(path);
because you get the class of your Toolbar class, which is where all your other classes/files are located.
This doesn't work:
URL url = System.class.getResource(path);
because the "System" class is found in the JDK not with your application classes.
I would guess you could try:
URL url = Utils.class.getResource(path);

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.

JFileChooser not showing up

I have a method that takes a txt file as an input. I used to use string by typing the direct path to the file.
But it became burdensome whenever I tried to use different file for an input. I try implementing JFileChooser but with no luck.
This is the code, but nothing happening.
public static JFileChooser choose;
File directory = new File("B:\\");
choose = new JFileChooser(directory);
choose.setVisible(true);
File openFile = choose.getSelectedFile();
FileReader fR = new FileReader(openFile);
BufferedReader br = new BufferedReader(fR);
As per Java tutorial on How to Use File Choosers:
Bringing up a standard open dialog requires only two lines of code:
//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);
The argument to the showOpenDialog method specifies the parent
component for the dialog. The parent component affects the position of
the dialog and the frame that the dialog depends on.
Note as per docs it can also be:
int returnVal = fc.showOpenDialog(null);
If the parent is null, then the dialog depends on no visible window,
and it's placed in a look-and-feel-dependent position such as the
center of the screen.
 
Also have a read on Concurrency in Swing if you haven't already.
No blocking code (as David Kroukamp suggest). It solves "not showing up" problem.
Runnable r = new Runnable() {
#Override
public void run() {
JFileChooser jfc = new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if( jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ){
selected = jfc.getSelectedFile();
}
}
}
SwingUtilities.invokeLater(r);
I personally found that the first dialog would show, but subsequent dialogs wouldn't show. I fixed it by reusing the same JFileChooser with this code.
JFileChooser jfc = new JFileChooser();
File jar = selectFile(jfc, "Select jar to append to");
File append = selectFile(jfc, "Select file to append");
//When done, remove the window
jfc.setVisible(false);
public static File selectFile(JFileChooser jfc, String msg) {
if (!jfc.isVisible()) {
jfc.setVisible(true);
jfc.requestFocus();
}
int returncode = jfc.showDialog(null, msg);
if (returncode == JFileChooser.APPROVE_OPTION) return jfc.getSelectedFile();
return null;
}
For JFileChoosers, you're supposed to call objectName.showOpenDialog(Component parent) or objectName.showOpenDialog(Component parent). These methods will return an integer, which you can use to compare to the static constants set in JFileChooser to determine whether the user clicked cancel or open/save. You then use getSelectedFile() to retrieve the file that the user has selected.
Ex (There might be small errors):
class Example {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
File selected;
if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selected = jfc.getSelectedFile();
}
}
}
The Java API is a great resource for figuring out what objects can do what, and how. Here's the page for JFileChoosers
The API pages are usually found when you Google the object name. They're usually the first ones that come up as a result as well.

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.

java form button order execution

i write a method to create a form(3 buttons and a textBox), then i call it in main.
but when i run program, before i enter information in the form (method form6 ),
Other commands that are executed! "s4 and ontname chenged in the form".
this is a part of my code:::::::::::
//////////////////////////////////////////////////////////////////////////
public static void main(String[] args) {
System.out.println("*begin main*"); // call form method
String s4= form6(); // s4 is returned by method.
System.out.println("s3333*"+s4);
System.out.println("ont:"+ontname);//it's global }
//////////////////////////////////////////////////////////////////////////
i have 2 questions:::
1--- While the form is running, other commands are executed!
What is their order execution?
2. --- i want to define a button to when i click it,it closes the form.
thanks all.
If I get your code correctly, ontname is either (1) a class member (declared outside a method) or (2) a local variable, which is declared in the method that contains this code snippet.
In both cases there is no need to "return" ontname just because it is not declared inside the anonymous ActionListener instance.
The following example illustrates a typical pattern for this problem:
public void someMethod() {
// ...
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
setOntName(selFile.getPath()); // <-- here we call another method
}
});
// ...
}
void setOntName(String ontName) {
// do something with ontName
}
Alternativly: declare ontName as a static class member (only):
private static String ontName = ""; // <-- accessible from main method
public static void main(String[] args) {
// ...
}
// more methods.
You can't return a value in this Method because the ActionListenerInterface does not allow this. But you can call another method from within the actionPerformed() method and pass the ontname to it.
You can also close the third button in the new method. Or define the third button as final and use it in the actionPerformed() method.
E.g.
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
anotherMethod(ontname);
}
});
private void anotherMethod(String path) {
//doSomething with the path
//close third button here
}
You could probably define your variable ontname as global, outside of your function:
var ontname = null;
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
// ...
ontname=selFile.getPath();
}
});
// ...
System.out.println("filepath: "+ontname);
If you want to remember the values, then they should be class level variables.
But, generally, you would want to pass these to some other method to do some processing on them (or, say, persist them in a file). You can pass these as parameters to the other method.
(The second one is better in most cases, I don't know much about your app, so I am unable to give one answer)
There are other problems with your code:
You need to check whether the use has clicked the "Ok" or "Cancel" button in the open dialog to decide whether to get the file or not.
String filename = File.separator+"c:"; does not really make sense. Perhaps you meant String filename = "c:"+File.separator; But even this is not very useful. File.separator is for getting the platform specific file separator char (\ in Windows, / on linux) but since you are hard coding c:, you are anyway constrainting your app to Windows. You might want to have a better platform independent way (start at the "default" path, new JFileChooser() without arguments, and then remember the path the user last used, and proceed from there)
If the argument to the showOpenDialog method is your parent frame, then the dialog would be centered on the parent frame, and would, in most cases, look nicer.
You might also want to relook your variable names.
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String filename = File.separator+"c:";
JFileChooser fc = new JFileChooser(new File(filename));
int option = fc.showOpenDialog(null);
if(option = JFileChooser.APROVE_OPTION)
{
File selFile = fc.getSelectedFile();
String ontname=selFile.getPath();
System.out.println("filepath: "+ontname); //it works correctly.
doSomeOperation(ontname); //Or, declare ontname as a class level variable.
}
}
});

Categories

Resources