I am building Java SWT application. As a part of whole process i am working on an excel file which have specific format to process things. What i want is a link on my JFrame which triggers download of a sample excel file stored in my project without local or internet dependency. I don't know how exactly i can do this.
I have tried this FileUtils.copyURLToFile but it is throwing null pointer exception. I am showing my code. Any help would be greatly appreciated.
public void actionPerformed(ActionEvent arg0) {
log("clicked to download");
String temp_path = System.getProperty("user.dir")+"\\resources\\EmailSheet.xlsx";
log("path = " + temp_path);
URL inputUrl = getClass().getResource(temp_path);
log("URL = " +inputUrl.toString());
File dest = new File("D:/new_file.xlsx");
try {
FileUtils.copyURLToFile(inputUrl, dest);
} catch (IOException e) {
log("Error saving sample file : " + e.getMessage().toString());
e.printStackTrace();
}
}
My Console is printing this error
Mon Oct 03 09:14:29 IST 2016 : clicked to download
Exception in thread "AWT-EventQueue-0" Mon Oct 03 09:14:29 IST 2016 : path = \resources\EmailSheet.xlsx
java.lang.NullPointerException
at tech.excelemail.com.TechExcelEmailApp$7.actionPerformed(TechExcelEmailApp.java:221)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I want to know if there is mistake in my code. or if i am going the wrong way. Ask me anything that if u think something missing unspecified.
Thanks in advance.
It's rather hard to believe that System.getProperty("user.dir") really returned an empty string, as your trace appears to suggest. Is this the real code?
In any case resources are named relative to the CLASSPATH, not the file system, so user.dir has nothing to do with it. They aren't files. And they don't use backslashes. Use forward slashes. And make sure that the resource named is present under that name in the JAR file.
Related
First time posting but here it goes. I am attempting to to make a program that reads all files in a drive and hash those files in order to spot potential differences in a "corrupt drive". The program functions fine for all purposes except when encountering files with special permission needs. I have spent days trying to resolve this and have read many stack posts but none that i have found have covered my specific issue. I have tried granting permission through set read and write but does nothing.
I think i found a promising library through java.security.allpermissions but finding examples of how to set it up simply / clearly for a method call has been unfruitful.
The following is the method giving me a hard time.
private static String hash(File f, String name) throws NoSuchAlgorithmException, IOException {
if(f.isDirectory() == true) {
return "";
}
InputStream is = Files.newInputStream(Paths.get(f.getAbsolutePath()));
output = DigestUtils.sha256Hex(is);
output = DigestUtils.sha256Hex(name + output);
return output;
}
sample output + stack trace:
F:\
F:\$Recycle.Bin
F:\$Recycle.Bin\S-1-5-18
F:\$Recycle.Bin\S-1-5-18\desktop.ini
F:\$Recycle.Bin\S-1-5-21-3562049501-1359381880-3951677873-1001
F:\$Recycle.Bin\S-1-5-21-3562049501-1359381880-3951677873-1001\desktop.ini
F:\$Recycle.Bin\S-1-5-21-4029137503-3596887599-1249178651-1001
F:\$Recycle.Bin\S-1-5-21-4029137503-3596887599-1249178651-1001\desktop.ini
F:\Documents and Settings
Issue exploring folder:
java.nio.file.AccessDeniedException: F:\hiberfil.sys
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.Files.newByteChannel(Unknown Source)
at java.nio.file.spi.FileSystemProvider.newInputStream(Unknown Source)
at java.nio.file.Files.newInputStream(Unknown Source)
at Core.Main.hash(Main.java:47)
at Core.Main.construct(Main.java:91)
at Core.Main.run_construct(Main.java:129)
at Core.Display$SwingAction.actionPerformed(Display.java:297)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I am making an application in which one of the features the constructor requires a picture. The picture is selected using the JFileChooser obviously and then displayed on a JLabel. My problem is I do not have security privilege to access the picture. I tested to see if I do get the absolute path and if the file exists and I did get the path and true for the latter. So how do I give my app access to at least just get pictures?
My code
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FileNameExtensionFilter("jpg","png"));
int returnVal = chooser.showOpenDialog(diag);
if(returnVal == JFileChooser.APPROVE_OPTION) {
weaponImg = new ImageIcon(TempDialogs.class.getResource(chooser.getSelectedFile().getAbsolutePath()));
weaponPic.setIcon(weaponImg);
weaponPic.revalidate();
weaponPic.repaint();
My error
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at ui.TempDialogs$5.mouseClicked(TempDialogs.java:171)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
java security not allowing me ..
This has nothing to do with security, despite the stack trace mentioning 'security' in some of the lines. The real problem is at the very top of the stack trace, ..
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
And I expect it all starts with this line of code..
weaponImg = new ImageIcon(TempDialogs.class.getResource(chooser.getSelectedFile().getAbsolutePath()));
Which is both wrong and unnecessarily convoluted.
Get resource is for producing an URL from resources on the application's class path, it is neither needed nor useful for files.
So in this case of trying to access a file, we can use either a File object, or a String the represents a path to a file on the file system. So it could be shortened to:
weaponImg = new ImageIcon(chooser.getSelectedFile().getAbsolutePath()); // use String
But as alluded to, it could also be loaded as a plain File, so this would also work:
weaponImg = new ImageIcon(chooser.getSelectedFile()); // use File!
I am attempting to have my Java Application open a PDF file when the user clicks button. However, I get the stack trace below stating that the file doesn't exist. Bascially I would like to be able to load this file when the user makes the selection.
Below I will have the stack trace then the code and a screenshot of the path.
StackTrace:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \RFBase-TD_Communications\src\pdf\RFTDAnalyzerHelpFile.pdf doesn't exist.
at java.awt.Desktop.checkFileValidation(Unknown Source)
at java.awt.Desktop.open(Unknown Source)
at GUI.rfbgui.openPDF(rfbgui.java:787)
at GUI.rfbgui.access$7(rfbgui.java:773)
at GUI.rfbgui$6.actionPerformed(rfbgui.java:921)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Code:
private static void openPDF()
{
File pdfHelpFile = new File("/RFBase-TD_Communications/src/pdf/RFTDAnalyzerHelpFile.pdf");
try
{
Desktop.getDesktop().open(pdfHelpFile);
}catch(IOException ex)
{
ex.printStackTrace();
}
}
I have some general advice for how to handle these situations. Files were one of the things I got very frustrated with when starting to learn to program.
Use System.getProperty("user.dir"); This can be very helpful especially when you do not know where the program is going to be run from, or you have a specific file structure.
In Java, I generally recommend using "\" instead of "/".
Run a sanity check on the file you are attempting to load. Specifically check if it is null, .isFile(), etc. You never know what you might get back, so its good to take a peak before accidently crashing your program.
Here is some links for similar questions that might help you out;
How should I load files into my Java application?
Getting the Current Working Directory in Java
Getting the inputstream from a classpath resource (XML file)
File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
or
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
I try to load a file named config.properties in the package config.
A snippet of my code in Main.java:
//Read config.properties
Properties properties = new Properties();
System.out.println(Main.class.getClassLoader().getResource("config/config.properties").toString());
InputStream propertiesFile = Main.class.getClassLoader().getResourceAsStream("config/config.properties");
properties.load(propertiesFile);
This however gives me a NullPointerException. But when I load img/background/background.png I use: (from Panel.java)
background = new ImageIcon(this.getClass().getClassLoader().getResource("img/background/background.png")).getImage();
This works fine. I've read a lot of questions on stackoverflow already, but can't find a solution to my problem. I do not see the difference between the loading of the background image or the properties file, other than the fact that the properties file is loaded in a static context. But as far as I can see, this should work.
What am I forgetting?
EDIT: I just ran System.out.println(Main.class.getClassLoader().getResource("config/config.properties").toString());, which printed the correct path to config.properties.
Stacktrace: java.lang.NullPointerException
at main.Main.startGame(Main.java:70)
at main.gui.panel.MenuPanel$1.actionPerformed(MenuPanel.java:31)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Main.java - line 70:
int maxFPS = Integer.getInteger(properties.getProperty("FPS"));
config.properties:
FPS=45
fpsCap=1
The problem wasn't with the getResourceAsStream("config/config.properties"), but with the way I read the properties. Property FPS is written as a String, to make this in an int I had to use Integer.parseInt(), instead of Integer.getInteger().
Try getting it from the current thread context loader:
Properties properties = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try (InputStream in = loader.getResourceAsStream("config/config.properties")) {
properties.load(in);
} catch (IOException e) {
throw new IllegalStateException("Cannot start, properties not found.");
}
This code compiles for JDK 7+, since it uses auto closeable, but can be translated to previous JDK version by moving the resource loader statement to be in in the try-catch clause.
When using a Java robot, when sending a slash or backslash throws an exception.
For example:
public void slash() throws AWTException {
Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_SLASH);
rob.keyRelease(KeyEvent.VK_SLASH);
}
public void backSlash() throws AWTException {
Robot rob = new Robot();
rob.keyPress(KeyEvent.VK_BACK_SLASH);
rob.keyRelease(KeyEvent.VK_BACK_SLASH);
}
Then, when I want to type those, I use:
public void type() {
try {
slash();
} catch (AWTException e) { System.out.println("Exception when typing slash."); }
try {
backSlash();
} catch (AWTException e) { System.out.println("Exception when typing back slash."); }
}
I get two error messages in my console. By the way, all other keystrokes I tried to send worked fine.
I get the follwowing stacktrace for slash:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at com.paschoalinoto.bruno.pastescript.Paste.slash(Paste.java:23)
at com.paschoalinoto.bruno.pastescript.Paste.type(Paste.java:36)
at com.paschoalinoto.bruno.pastescript.MainGUI$4.actionPerformed(MainGUI.java:113)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Backslashes work, but also throw an IllegalArgumentException:
java.lang.IllegalArgumentException: Invalid key code
at sun.awt.windows.WRobotPeer.keyPress(Native Method)
at java.awt.Robot.keyPress(Unknown Source)
at com.paschoalinoto.bruno.pastescript.Paste.press(Paste.java:198)
at com.paschoalinoto.bruno.pastescript.Paste.paste(Paste.java:173)
at com.paschoalinoto.bruno.pastescript.Paste.finalPaste(Paste.java:227)
at com.paschoalinoto.bruno.pastescript.MainGUI$4.actionPerformed(MainGUI.java:113)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Is there any way I can send slash and backslash keystrokes?
Okay, I have found a solution that may be handy for users working with different keyboard layouts. It uses Alt codes.
public static void alt(int event1, int event2, int event3, int event4) throws Exception {
Robot bot = new Robot();
bot.delay(50); //Optional
bot.keyPress(KeyEvent.VK_ALT);
bot.keyPress(event1);
bot.keyRelease(event1);
bot.keyPress(event2);
bot.keyRelease(event2);
bot.keyPress(event3);
bot.keyRelease(event3);
bot.keyPress(event4);
bot.keyRelease(event4);
bot.keyRelease(KeyEvent.VK_ALT);
}
Then you call it like this:
For back slashes:
alt(KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD9, KeyEvent.VK_NUMPAD2);
For normal ones:
alt(KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD0, KeyEvent.VK_NUMPAD4, KeyEvent.VK_NUMPAD7);
No exceptions.
Also works for all other characters. But make sure you have Num Lock on when using this.
(Sorry I should mention this isn't quite an answer, just saying that it does work for me so I'm guessing it's a configuration issue or something--but I thought that it was something others might find handy. It should be a comment but for technical reasons I have to make it an answer)
I hadn't messed with the Robot class and just spent a FUN half hour messing around and bulding some stuff on top of this cool java class.
For me sending slash and backslash work fine. Since the VK_??? stuff maps pretty well to the ASCII characters, you can send '\' or '/' and it should work too.
I used Groovy because that's what I play in these days, but here's a nice example and a bunch of reusable code I just came up with. It's written as a script but could easily be converted to a class in either Groovy or Java (and I will do so soon).
This must be run from a "Priviliged" shell (for instance right-click on the command prompt and select "Run as administrator").
also it MUST have time for you to let go of the keyboard! (Learned that the hard way), so if you use groovyShell and use alt-r to run it, be sure to put a 1 second delay before sending the first keys or your ALT will become part of the keys pressed.
import java.awt.*
import java.awt.event.*
import static java.awt.event.KeyEvent.*
r=new Robot()
r.autoWaitForIdle = true
r.autoDelay=200 // Usually works with 0 but sometimes that's too fast.
// This will alt-tab you to your "Previous" app. While testing I edited this in notepad++
// then tabbed out to a shell to execute it, this tabbed back into my editor and typed
// the "test" text.
alt VK_TAB
send "backslash=\\ \nforward slash =/"
// This will send any string
def send(String s)
{
def difference = ("a" as Character) - ("A" as Character)
s.each {
Character c=it as Character
if(c.isUpperCase()) {
shift c
} else if(c.isLowerCase()) {
send(c - difference)
}
else send(c)
}
}
// These will work for integers and chars, NOT strings
def send(key)
{
press(key as Integer)
release(key as Integer)
}
def alt(key)
{
press VK_ALT
send key
release VK_ALT
}
def shift(key)
{
press VK_SHIFT
send key
release VK_SHIFT
}
def press(key)
{
r.keyPress(key as Integer)
}
def release(int key)
{
r.keyRelease(key as Integer)
}