I have a problem with loading image with java 2ME. I have a image file "picture.png" in location drive "C:". After that I wrote my like this to show image from this location.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.io.*;
public class ImageMidlet extends MIDlet implements CommandListener{
private Display display;
private Command exitCommand;
private Command backCommand;
private Command okCommand;
private Form form;
private ImageItem imageItem;
private Image image;
public ImageMidlet(){
display = Display.getDisplay(this);
form=new Form("");
exitCommand = new Command("Exit", Command.EXIT, 1);
backCommand = new Command("Back", Command.BACK, 2);
okCommand = new Command("OK", Command.OK, 3);
try {
image=Image.createImage("/picture.png");
imageItem=new ImageItem(null,image,ImageItem.LAYOUT_NEWLINE_BEFORE,"");
}
catch(IOException ex){
}
form.append(imageItem);
form.addCommand(okCommand);
form.addCommand(exitCommand);
form.addCommand(backCommand);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c,Displayable d){
}
public void startApp() {
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
It shows me this error:
Unable to create MIDlet Test.ImageMidlet
java.lang.NullPointerException
at javax.microedition.lcdui.Form.append(Form.java:638)
at Test.ImageMidlet.<init>(ImageMidlet.java:39)
at java.lang.Class.runCustomCode(+0)
at com.sun.midp.midlet.MIDletState.createMIDlet(+34)
at com.sun.midp.midlet.Selector.run(Selector.java:151)
I am starting learn to develop, so please guide to do this.
Image.createImage(String name) loads the given image as a resource. Resources are loaded with Class.getResourceAsStream(name), which looks up the resources from classpath, not from your file system root.
You should put the image file in your classpath, which is usually the final application .jar file. Usually a folder called resources or res is created under the project, where the images are placed. The contents of this folder are then copied to the .jar file. In development phase you should be able to append your resource folder to the classpath with a command-line parameter (java -cp resources in Java SE) or with a similar IDE setting.
If you are really interested in loading the images from actual file system, you can use optional FileConnection API (http://developers.sun.com/mobility/apis/articles/fileconnection/). The handset support for this API is limited though. For static images the classpath is the way to go.
As msell said - You can't access images from Your computer. Make sure that You have included the given image in midlet jar file. If You try to access it using '/picture.png', then it should be located a the root directory in jar.
First of all place your image in default package.
I have placed "My Network Places.png" in default package.
Then create MIDlet named "ImageItemExample"
then copy below code in that MIDlet file.
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class ImageItemExample extends MIDlet implements CommandListener{
private Display display;
private Command exit;
private Form form;
private ImageItem logo;
public ImageItemExample(){
form = new Form("Image Item");
exit = new Command("Exit", Command.EXIT, 0);
try{
logo = new ImageItem(null, Image.createImage("/My Network Places.png"),
ImageItem.LAYOUT_CENTER | ImageItem.LAYOUT_NEWLINE_BEFORE |
ImageItem.LAYOUT_NEWLINE_AFTER, "Roseindia");
form.append(logo);
}catch(IOException e){
form.append(new StringItem(null, "Roseindia: Image not available: "+ e));
}
}
public void startApp(){
display = Display.getDisplay(this);
form.addCommand(exit);
form.setCommandListener(this);
display.setCurrent(form);
}
public void pauseApp(){}
public void destroyApp(boolean unconditional){
notifyDestroyed();
}
public void commandAction(Command c, Displayable d){
String label = c.getLabel();
if(label.equals("Exit")){
destroyApp(true);
}
}
}
My guess is that
image=Image.createImage("/picture.png");
throws an exception which prevents the creation of a new object of type ImageItem which leaves your imageItem variable as null. This gives you the null pointer exception.
Isn't your file Picture.png and not Pictur.png?
Verify that the file picture.png actually exists
depending on the device emulator/IDE there should be a way to set the "HOME" directory for the device. In your case, this would be "C:\"
Related
We are trying cucumber serenity framework for end to end tests. I am fairly new the technology and I tired this simple code below.
actor.attemptsTo(Enter.theValue(path).into(Upload));
where path is the location of file i am trying to upload using browser's upload widget.Has anyone ever managed to perform actions like this using serenity screen play pattern.
Its really making us think of giving up serenity and just use cucumber-selenium framework as I can easily perform this using Upload.sendkeys(path);
Any help is much appreciated. Thanks in advance.
AS requested: Listing Steps:
public class ListingSteps
{
#Before
public void set_the_stage() {
OnStage.setTheStage(new OnlineCast());
}
#Given("^(.*) is able to click import products$") public void userIsAbleToClick(String actorName) throws Throwable
{
theActorCalled(actorName).wasAbleTo(Start.theApplication());
}
#When("^s?he imports a single item successfully$") public void heImportsASingleItemSuccessfully() throws Throwable
{
theActorInTheSpotlight().attemptsTo(Import.spreadsheet());
}
#Then("^(.*) are listed on ebay and amazon with all the right information$") public void itemsAreListedOnEbayAndAmazonWithAllTheRightInformation(String actorName, String SKU)
throws Throwable
{
//pending
}
Ignore then for now as its work in progress.
Import class:
public class Import implements Task
{
protected String path =
"C:\\somePathToFile\\populated_excel.xlsx";
public static Import spreadsheet()
{
return instrumented(Import.class);
}
#Override public <T extends Actor> void performAs(T actorName)
{
actorName.attemptsTo(Click.on(Products.ProductsScreen));
actorName.attemptsTo(Click.on(Products.Upload));
actorName.attemptsTo(Enter.theValue(path).into(Browse).thenHit(Keys.RETURN));//this is the line which is giving errors
actorName.attemptsTo(Click.on(Products.UploadButton));
}
}
Target Browse
public class Products
{
public static Target Browse = Target.the("browse file").locatedBy("//input[#type='file']");
}
Did you try removing these lines?
actorName.attemptsTo(Click.on(Products.ProductsScreen));
actorName.attemptsTo(Click.on(Products.Upload));
You don't need to open the upload file component, only write the file path directly to the input file element and perform the submit.
The way I managed to get this working was by using the FileToUpload class:
import net.thucydides.core.pages.components.FileToUpload;
FileToUpload fileToUpload = new FileToUpload(driver, fileName);
fileToUpload.fromLocalMachine().to(webElement);
I got this working with a simple:
import java.nio.file.*;
Path data = null;
try {
data = Paths.get(ClassLoader.getSystemResource(file).toURI());
} catch (URISyntaxException ignore) {}
ACTOR.attemptsTo(Upload.theFile(data).to(target));
file is an actual file that exists on your classpath, in src/test/resources if you have a Maven project.
target is something like:
Target.the("Image upload").located(By.xpath("//input[#type='file']"));
I wish to do what the title says.
Part Solution:
For example in Windows you can use the code below to open a file in the default explorer and highlight it.
(although it needs modification for files containing spaces):
/**
* Opens the file with the System default file explorer.
*
* #param path the path
*/
public static void openFileLocation(String path) {
if (InfoTool.osName.toLowerCase().contains("win")) {
try {
Runtime.getRuntime().exec("explorer.exe /select," + path);
} catch (IOException ex) {
Main.logger.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
Useful Links:
Links which are similar but no way dublicates or not answered:
How to use java code to open Windows file explorer and highlight the specified file?
Open a folder in explorer using Java
How can I open the default system browser from a java fx application?
More explanation:
Is there a way to do it using JavaFX ?
If not at least i need a link or some way to make the app system
independence.I mean i don't know the default explorer for every OS
that the application is going to work , i need a link or help doing that.
Do i need to write a ton of code to do this?
Is out there any library for doing that?
Do Java9 support that?
Finally:
It is very strange that for so common things i can't find answers and libraries .
Example of highlighted or selected in Windows 10:
Windows
Runtime.getRuntime().exec("explorer /select, <file path>")
Linux
Runtime.getRuntime().exec("xdg-open <file path>");
MacOS
Runtime.getRuntime().exec("open -R <file path>");
Since Java 9 it's possible with the new method browseFileDirectory, so your method would state:
import java.awt.Desktop;
import java.io.File;
...
/**
* Opens the file with the System default file explorer.
*
* #param path the path
*/
public static void openFileLocation(String path) {
Desktop.getDesktop().browseFileDirectory(new File(path));
}
For more information, refer to the javadoc:
https://docs.oracle.com/javase/10/docs/api/java/awt/Desktop.html#browseFileDirectory(java.io.File)
The following is a partial answer showing you how to open the system folder you desire, but not how to highlight a specific file since I do not believe it is possible to highlight a file in a system folder, because that is probably a system OS function that cannot be accessed by Java.
This is written in Javafx code
In your Main class make a variable for Hostservices. Note that "yourFileLocation" is the address of the folder to the file, and SettsBtn is a button that exists somewhere which the user clicks to execute the code:
public class Main extends Application{
static HostServices Host; //<-- sort of a global variable
//some code here to make your GUI
public Main() {
//more code here to initialize things
}
public void start(Stage primaryStage) throws Exception {
//some code here to set the stage
//This code here opens the file explorer
SettsBtn.setOnMouseClicked(e-> {
Path partPath = Paths.get("yourFileLocation");
Host = getHostServices();
Host.showDocument(partPath.toUri().toString());
});
}
}
Note that you could directly open the file by making a string to the file location and the file name with its extension, such as:
Path partPath = Paths.get("yourFileLocation"+"\\"+"yourFileName.ext");
As of Java 17 the Desktop::browseFileDirectory method is still not supported on Windows 10 or later.
The historic reason is that Apple originally implemented these native Desktop integration features for Mac OS X in the com.apple.eawt package back when Apple itself was still maintaining the JDK for Mac OS X. All of that was ported into java.awt.Desktop for Java 9 as per JEP 272: Platform-Specific Desktop Features and so I guess some of these features are still only implemented for Mac OS X to this day.
Fortunately, Windows 10 does have a SHOpenFolderAndSelectItems function that we can call via JNA like so:
public interface Shell32 extends com.sun.jna.platform.win32.Shell32 {
Shell32 INSTANCE = Native.load("shell32", Shell32.class, W32APIOptions.DEFAULT_OPTIONS);
HRESULT SHParseDisplayName(WString pszName, Pointer pbc, PointerByReference ppidl, WinDef.ULONG sfgaoIn, Pointer psfgaoOut);
HRESULT SHOpenFolderAndSelectItems(Pointer pidlFolder, WinDef.UINT cidl, Pointer apidl, WinDef.DWORD dwFlags);
}
public class Shell32Util extends com.sun.jna.platform.win32.Shell32Util {
public static Pointer SHParseDisplayName(File file) {
try {
PointerByReference ppidl = new PointerByReference();
// canonicalize file path for Win32 API
HRESULT hres = Shell32.INSTANCE.SHParseDisplayName(new WString(file.getCanonicalPath()), null, ppidl, new WinDef.ULONG(0), null);
if (W32Errors.FAILED(hres)) {
throw new Win32Exception(hres);
}
return ppidl.getValue();
} catch (Exception e) {
throw new InvalidPathException(file.getPath(), e.getMessage());
}
}
public static void SHOpenFolderAndSelectItems(File file) {
Pointer pidlFolder = SHParseDisplayName(file);
try {
HRESULT hres = Shell32.INSTANCE.SHOpenFolderAndSelectItems(pidlFolder, new WinDef.UINT(0), null, new WinDef.DWORD(0));
if (W32Errors.FAILED(hres)) {
throw new Win32Exception(hres);
}
} catch (Exception e) {
throw new InvalidPathException(file.getPath(), e.getMessage());
}
}
}
I'm currently trying to develop a game, and the file path is changing when I export it.
Here is the code:
package random;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Troll extends JFrame{
/**
*
*/
private static final long serialVersionUID = 4176461585360667597L;
public static BufferedImage img;
public static void main(String[] args){
File f = new File("troll.png");
try{
if(f.exists()){
System.out.println("ITS THERE! :D");
img = ImageIO.read(f);
} else {
System.out.println("DOESNT EXIST, REAL PATH IS: " + f.getAbsolutePath() );
}
}catch(Exception e){
e.printStackTrace();
}
new Troll();
}
public Troll(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public void paint(Graphics g){
g.drawImage(img, 500, 350, this);
}
}
When I run it through Eclipse ( The IDE I'm using ), it's running fine and it's showing the image. When I export it as a jar and convert it to an exe using Jar2Exe Software, the image does not appear and in the console it says that the absolute path for the image is on my Desktop. But when I open the exe using 7-Zip, the picture is in the exe.
How can I export it so that when the user runs it, the program can find the file path and show the image, instead of it thinking that it's on my desktop?
If you want to publish it as a jar then you need to use the Jar-specific API for reading your file. See eg. How to read a file from a jar file? (and you need to configure Eclipse to put the picture in the jar, which it sounds like you're already doing).
Also you should let us know whether it works when it's in a jar but not as an exe, that will help us narrow down where the problem may be.
I hope this is not a troll (lol)
img = ImageIO.read(this.getClass().getResource("/troll.jpg"));
You are in a jar, there is no resource file.
See that link as well: http://www.jar2exe.com/createdexe/integrate/protect
Thread.currentThread().getContextClassLoader().getResource("hello/yes.gif");
I have been trying to export a standalone application for Mac using the "Export Application" function in Processing. The simple application, which involves updating a float value on the screen that corresponds to the y-axis position of a hand detected by a Leap Motion, works perfectly well within Processing. However, once I export the application and try to run it, the app opens for a brief second and quickly closes. I have exported applications from Processing successfully before, but not one that uses the Leap SDK. I am using the LeapMotion library for Processing to access the Leap SDK: https://github.com/heuermh/leap-motion-processing. Here is my code:
import processing.core.*;
import com.leapmotion.leap.processing.*;
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.Listener;
public class Test extends PApplet {
Controller controller;
MyListener listener;
float position = 0.0f;
class MyListener extends Listener {
public void onFrame(Controller controller) {
if (!controller.frame().hands().isEmpty()) {
position = controller.frame().hands().leftmost().palmPosition().get(1);
}
}
}
public void setup() {
size(600,600);
controller = new Controller();
listener = new MyListener();
controller.addListener(listener);
}
public void draw() {
background(0);
textAlign(CENTER,CENTER);
textSize(50);
text(position, 300,300);
}
public static void main(String args[]) {
PApplet.main("Test");
}
}
When I export the application, the contents of the application are as follows:
Info.plist
Java
-core.jar
-gluegen-rt-natives-macosx-universal.jar
-gluegen-rt.jar
-jogl-all-natives-macosx-universal.jar
-jogl-all.jar
-LeapJava.jar
-LeapMotion.jar
-libLeap.dylib
-libLeapJava.dylib
-Test.jar
MacOS
-Test
Plugins
-jdk1.7.0_45.jdk
Resources
-en.lproj
-sketch.icns
PkgInfo
Any help would be greatly appreciated!
P.S. I've already tried bundling the program into a runnable JAR file.
I have created a Mac Java Swing application, and i have set a file extension(*.pkkt) for it in the "Info.plist" file, so when double clicking that file it opens my application.
When i do that the program runs fine. Now i need to load the (*.pkkt) project in the program, but the file path is not passed as an argument to the main(...) method in Mac as happens in Windows Operating System.
After some search i found an Apple handling jar "MRJToolkitStubs" that has the MRJOpenDocumentHandler interface to handle such clicked files. I have tried using it to load that file by implementing that Interface in the main program class, but it is not working. The implemented method is never called at the program start-up.
How does this Interface run ?
------------------------------------------------- Edit: Add a Code Sample
Here is the code i am using :
public static void main( final String[] args ) {
.
.
.
MacOpenHandler macOpenHandler = new MacOpenHandler();
String projectFilePath = macOpenHandler.getProjectFilePath(); // Always Empty !!
}
class MacOpenHandler implements MRJOpenDocumentHandler {
private String projectFilePath = "";
public MacOpenHandler () {
com.apple.mrj.MRJApplicationUtils.registerOpenDocumentHandler(this) ;
}
#Override
public void handleOpenFile( File projectFile ) {
try {
if( projectFile != null ) {
projectFilePath = projectFile.getCanonicalPath();
System.out.println( projectFilePath ); // Prints the path fine.
}
} catch (IOException e) {}
}
public String getProjectFilePath() {
return projectFilePath;
}
}
As mentioned in the comment above "getProjectFilePath()" is always Empty !
On Java 9, use Desktop.setOpenFileHandler()
The proprietary com.apple.eawt packages have been removed from recent versions of Java and has been incorporated into various methods in the Desktop class. For your specific example:
import java.awt.desktop.OpenFilesHandler;
import java.awt.desktop.OpenFilesEvent;
import java.io.File;
import java.util.List;
public class MyOpenFileHandler implements OpenFilesHandler {
#Override
public void openFiles​(OpenFilesEvent e) {
for (File file: e.getFiles​()) {
// Do whatever
}
}
}
Then elsewhere, add this:
Desktop.getDesktop().setOpenFileHandler(new MyOpenFileHandler());
The OpenFilesEvent class also has a getSearchTerm() method. Say that a person used Spotlight on macOS to search for the word "StackOverflow", then decided to open up a document. With this method, can you determine that "StackOverflow" was the word they searched for, and choose to do something with that (perhaps highlight the first occurrence of the word).
You're going to want to use the Apple Java Extensions.
They should be included in any JDK that runs on Mac OS X, but the documentation is kind of hard to get. See this answer for more details.
Specifically, you'll want to make an OpenFilesHandeler.
This code snippet should work:
import com.apple.eawt.event.OpenFilesHandeler;
import com.apple.eawt.event.AppEvent;
import java.io.File;
import java.util.List;
class MacOpenHandler implements OpenFilesHandeler {
#Override
public void openFiles(AppEvent.OpenFilesEvent e) {
List<File> files = e.getFiles();
// do something
}
}
And somewhere:
import com.apple.eawt.Application;
...
MacOpenHandeler myOpenHandeler = new MacOpenHandeler();
Application.getApplication().setOpenFileHandler(myOpenHandeler);