I'm trying to code a program in Java that automatically types each character in a string using the Robot class. I've used it to make a similar automated program a while ago (which I'll refer to as the 'previous project') that used 'keyPress()'. This and most, if not all, of the other methods for the Robot class which I needed to use worked perfectly.
Now I've started and 'keyPress()' isn't typing anything, regardless of the KeyEvent I pass as an argument. I thought I had written the code incorrectly, so I ran my previous project just to make sure it worked, but it didn't.
Here's the snippet of code I used for the previous project and my current one (which you can also use to test this).
EDIT: Try the on a text editor or anything that functions like a text field. I've now shown the entire demo class.
// demo procedure
public class DemoClass() {
public static void main(String[] args) {
new DemoClass().run()
}
public void run() {
try {
Robot robot = new Robot();
for (int i = 1; i <= 30; i++) {
robot.keyPress(KeyEvent.VK_A);
robot.delay(100);
System.out.println("Typed key");
}
} catch (AWTException e) {
e.printStackTrace();
}
}
}
'Typed key' gets printed 30 times and no errors appear in the output either.
I've tried;
adding 'robot.keyRelease(KeyEvent.VK_A)' just after the key press,
allowing the program type in the software I want to automate,
allowing the program to type in the IDE I'm using and in a text editor,
allowing the program to click in the IDE and text editor (so I could see if only pressing keys was the issue).
None of these have produced results. I've checked the code from multiple sources (articles and videos), all of which have the same code stub. I've read that some software prevent Robot objects from typing/clicking in them, but both typing and clicking worked when I was developing my previous project.
So I woke up today and... the program works.
I still don't know why it wasn't working in the first place or how the problem fixed itself (magic?). Running the sudo command didn't seem to make a difference, and none of the software I'm dealing with prevent a Robot object from automated typing/clicking.
It's most likely just a me-problem since other people managed to get it working. Since it's happened once it'll probably happen again.
Anyways, thanks to everyone that helped! If future readers have any ideas of why it didn't work then feel free to share them.
Related
I'm working on something in NetBeans, and I want to create an actionListener in a jTextPane for when the user presses Enter. However, I also need to input a String array (from a different subroutine within the source code) into the listener. But in NetBeans, events are generated automatically and I'm not allowed to edit this apparently extremely sensitive code. So, then, I tried typing up my own event thing (sorry about my terminology; I'm very new to GUI programming):
private void jTextPaneEnterPressed(KeyEvent evt, String[] stringArray)
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// do something when the user presses enter that involves the program knowing what stringArray is
}
}
But when I run the program, pressing Enter in the text pane does nothing. I understand that this is because there is no actionListener associated with jTextPaneEnterPressed, but NetBeans gives no option for such customized code.
So what I want to know is either how I can pass in my own parameters when NetBeans creates an event handler, or how I can write my own actionListener alongside this actionPerformed block.
(And for the record, this is not an import problem)
I have tried looking this up, but have found nothing specific, as all other similar issues are not relevant to NB. Any help would be greatly appreciated.
*EDIT: This may seem like a trivial problem to most, but I'm open to any actual answers that tell me how to get done what I am trying to do, though I would prefer to stick with NetBeans. All I need is for the action listener to know that this string array exists, because the program needs to deal with that array when the user presses Enter. I'm sorry I can't give any specific context, but it's too much to get into.
I am new to java, and I can't seem to figure out how I can get this simple code to work properly. I understand the code, and I have it typed exactly how the book has it. The code compiles with no errors, but it just doesn't print anything. I think the problem has to do with the main function or something, because when I right click the class in BlueJ and click on void main it will compile correctly.
Anyways, here's the code.
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
Am I doing something wrong in BlueJ, or is it supposed to be that way? Thanks!
When you're ready with the code, click on the Compile button.
If everything is fine, you will see a message on the bottom of the screen, saying Class compiled - no syntax errors. Then close the screen and go back to the project palette.
Right click on the class, and pick void main(String[] args). You will be prompted with a little screen, where you can provide some parameters. Don't provide any and just click OK.
If everything is fine, you will see the Terminal Window with the proper output.
There is nothing wrong with the code, I suggest you focus on the BlueJ documentation.
There is nothing wrong with the program. That's a regular "hello world" program.
There is nothing wrong with BlueJ. (Did you seriously think that BlueJ is incapable of running simple programs?)
There is most likely something wrong with the way you are using BlueJ ... but you've provided minimal information on that.
I suggest that you read the BlueJ documentation ... or follow this simple step-by-step example: http://www.cs.utexas.edu/~scottm/cs307/handouts/BlueJProjectInstructions.html
(It is also possible that you've not installed BlueJ correctly, but lets not start proposing wild theories without some evidence to support them ...)
I'm developing a Swing application and I need to flash the Windows taskbar. I can't use frame.requestFocus() because I don't want to steal focus from any other application.
I don't know if it applies to newer versions of Windows, but the .toFront() method used to flash the window if none of the current VM's windows were in the foreground.
This means that calling frame.toFront() on a minimized frame would always make it flash...
JNIWrapper with its winpack extension can do what you want.
The Demo on the site shows it in action.
You can either force-minimize your GUI and .toFront-en it:
Gui.frame.setState(Frame.ICONIFIED);
for (int i = 0; i < 3; i++) {
Thread.sleep(10);
Gui.frame.toFront();
Thread.sleep(10);
Gui.frame.setVisible(false);
Thread.sleep(10);
Gui.frame.toBack();
Thread.sleep(10);
Gui.frame.setVisible(true);
}
// be creative!!
which sadly will remove the focus from the active window. You could find out the active window and reactivate it afterwards. But still, the flashing will only last for about three seconds.
...or get down to the really root of the matter by using a DLL-call on FlashWindow. Calling dlls is not possible with clean Java code, you'll need the help of other programming languages, possible e.g. with JNA. Other than that, you could also write your own program in another language and call it from your Java application. I'll give an example in AutoHotkey below:
AutoHotkey Code:
if 0 != 1 ; note: in ahk, 1 corresponds args[1] and 0 corresponds args.length
{
msgbox, There needs to be ONE parameter passed over to this file, which is the name of the window that should be flashed.
ExitApp
}
programName = %1%
winget, hWnd, ID, %programName%
DllCall("FlashWindow",UInt,hWnd,Int,True)
compiled into a file called flash.exe, put into your Java working directory, you can call it from any function:
Runtime.getRuntime().exec("./flash.exe \"" + MyJFrame.getTitle() + "\"");
Alternatively, one could use the AutoHotkey.dll and access it within the Javacode (there are guides on how to do it on the internet), so there'd be no need for any external exe files.
If you still have problems achieving the flashing in the windows taskbar, please let me know!
The best way to do this:
if (!isFocused()) {
setVisible(false);
setVisible(true);
}
Using Swing per se, you very probably can't; that's a Widnows specific thing.
For example, say I have:
public Class Foo {
public final int X = 1;
public getX() {
return this.X;
}
}
Is it possible to write something to change the value of X for future runs of the program? So if the value the user wanted to use for X changes, and all they have is a compiled .jar file, they could run said method and then the value of X in the compiled code would be forever changed.
I am developing software for a research lab, at which I work temporarily. What the lab techs will be interacting with is just a bunch of JFrames. They don't know how to change it in the code and then recompile, etc. So I am trying to find the best way to have a "Change Defaults" button which would open a window for them that they can edit the default values, click "Save," and then the new value is what is used until they change it again. How can I do this?
java.util.Preferences, designed for this purpose, but involves a little work
My professor assigned a project where a simulation is ran through a GUI. To edit it, we need to create a "New" menu item. We haven't learned how to get data from a GUI, and our book does not cover it at all.
What I'm trying to do, is when the "New" command is hit, focus gets shifted back to the CMD prompt, where System.out. starts working again and prompts the user for input.
However, when I try to implement this, my program crashes. What can I do to solve this problem?
It doesn't look like you're keeping the reference to your newly created GUI. As far as I remember, Java will garbage collect the FoxGui object (as well as any other object) if there are no references to that object. Try creating a global variable to store the reference to your newly created FoxGui object. Something like...
FoxGui MyGUIRef;
public void actionPerformed(ActionEvent event)
{
System.out.println("Item: " + event.getActionCommand());
// File Menu Controls
if (event.getActionCommand().equals("New"))
{
MyGUIRef = runNew();
}
}
//Now returns a reference to FoxGui
private FoxGui runNew()
{
return new FoxGui(....)
}
Is the System.out in a terminal (non Java) window? If so, I think this would be much harder than you'd think.
I'd be tempted to redirect the System.in / System.out to a JTextPane on the GUI (That way, it would be much easier to change the focus etc. I think you need to try and explain what you're doing a little better in your question and perhaps post a stack trace when your program crashes.
Anyway, to do something when the "new" menu item is clicked you'd need to do:
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Code here to be performed when the item is clicked
}
});
You know what? I found a real simple solution, JOptionPane. I just needed to find a good example. It'll work fine for what I want. Thanks for all the help. I'll checkmark everyone who helped.
I know that it is very late answer, but anywhere...
There is only one way to do exactly what you want.
First you need to remember to run you project from CMD by java -jar jarname.jar
Catch click action and perform system.in
Information:
It is the only solution, because GUI never give focus to CMD, but if GUI runned from CMD you can use easily System.in.
Regards, Greg