Java Swing GUI Hidden Input - java

I made a simple JFrame with Swing. I want to know how I would go about making a non-visible input that would open up another JFrame I have in another class. (Like cheat codes in video games, you enter a combination and something happens.) I am not sure how to capture the user input without a text field.

You should use keybinding attached to your JFrame. You would want to store keystrokes as a String internally and after each keystroke, see whether the user has entered a recognizable cheat code or just listen for a return keypress as a delimiter for the code.
Keep in mind that if a component within that JFrame has focus and also implements the same key bindings, then that component will take precedence over the JFrame, effectively intercepting the keystrokes.

Related

Global Keylogger in Java Swing

I want to make a Keylogger happen in Java Swing. I could manage to make a simple keylogger that catches Keystrokes and writes them to a logfile, when the focus is on the Swing Window. Since the focus has to be on the window, is it possible to make an invisible JFrame, that is always on top?
Something like this:
public class Logger extends JFrame implements KeyListener
logger.setVisible(false);
logger.setAlwaysOnTop(true);
Is this possible in Java?
So, you want a key logger that record keystroke even the focus is not on Java Swing window, right?
Java itself cannot do this, but Java Native Interface (JNI) can. You could Google "Java System Hook" and download the JAR from Github. (https://github.com/kristian/system-hook/releases) In one word, it keeps recording your keyboard as long as the program runs, regardless of which window you are focusing on.
The way I use it: I wrote a program that keep running while I play games and it can print out whatever key I press in the game.

How do you append both pre-established text and user responses into a text area in Java?

I will do my best to explain-- I am trying to make a choose-your-own-adventure type game while using a TextField and a TextArea, where what is written in the TextField is appended into the TextArea (this I know how to do via ActionListener).
However, I need to have the TextArea start with a pre-written 'intro', which asks the user at the end if they want to continue or not. Therefore, I need it to be able to scan the user's response ('yes' or 'no') and choose the appropriate selection of pre-written text to follow.
I don't want to overwrite what is already in the TextArea, I want to add to it. I suppose what I'm confused about it how I'm supposed to lay out the entire file so that it functions properly, because the different choices for the adventure span different methods. Having
"String text = textField.getText();" only within the actionPerformed method means I can't use 'text' elsewhere, but moving that line up with my other variables tells me it can't reference the field before it's defined.
I am fairly new to Java and am working on this as a project for a non-programming school course. I've been through many iterations thus far and this is what seems to be my final attempt, as I've remade it repeatedly and don't have much time left. :(
Your questions/comments and my attempts to answer:
I am trying to make a choose-your-own-adventure type game while using a TextField and a TextArea, where what is written in the TextField is appended into the TextArea (this I know how to do via ActionListener).
As per my comment, be sure to create a Swing GUI which would use a JTextField and a JTextArea. You would then add your java.awt.event.ActionListener to the JTextArea, and the ActionListener would respond whenever the user pressed <ENTER> within the JTextField.
However, I need to have the TextArea start with a pre-written 'intro', which asks the user at the end if they want to continue or not. Therefore, I need it to be able to scan the user's response ('yes' or 'no') and choose the appropriate selection of pre-written text to follow.
This can be done easily, but sounds as if you may be trying to shoe-horn a linear console type program into a GUI. If so, consider reconsidering your program design since what works best for one often doesn't work well for another. If you do re-write, then you should consider redoing most including your program flow, but excepting perhaps the "model" portion of your previous program, the "business logic" that underlies everything.
I don't want to overwrite what is already in the TextArea, I want to add to it. I suppose what I'm confused about it how I'm supposed to lay out the entire file so that it functions properly, because the different choices for the adventure span different methods. Having "String text = textField.getText();" only within the actionPerformed method means I can't use 'text' elsewhere, but moving that line up with my other variables tells me it can't reference the field before it's defined.
Again as per comments a JTextArea has an append(String text) method that will add new text to existing text that is already displayed in your JText Area. So on that note, your ActionListener's actionPerformed method could be very simple and look something like:
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
textArea.append(text):
}
Although you may need to add line feeds, "\n" either before and/or after the text you are going to append.

Getting information from a text field JFrame form in a different class

Okay so I'm making a Library admin program and I have created a special frame where the user would enter details about a new book. However my method for adding a new book is in a separate class (methods). My question is how can I get the information the user enters in the text fields? Do I have to use something like getters, or is there an easier way. Also keep in mind that I am using the GUI layout (thing) in netbeans, and that I have already actually made the form. (I know it's frowned upon but I'm pressed for time and this is how we were taught.) This is a school project by the way. Thanks.
Okay so I'm making a Library admin program and I have created a special frame where the user would enter details about a new book.
Usually, a detail window should be a dialog, and likely a modal dialog. I suggest that you display this information in a modal JDialog, not a JFrame. Do this and it will make extracting information from the detail window much easier.
However my method for adding a new book is in a separate class (methods). My question is how can I get the information the user enters in the text fields? Do I have to use something like getters, or is there an easier way.
This begs the question -- what's so hard about using getters? And in fact his is exactly what I suggest that you use! Please note that your question essentially boils down to, "how can I get information on the state of one class's object from within another class's object", and for this getter methods are almost mandatory.
Also keep in mind that I am using the GUI layout (thing) in netbeans, and that I have already actually made the form. (I know it's frowned upon but I'm pressed for time and this is how we were taught.) This is a school project by the way.
This is unrelated to your current problem and should have little effect on its solution other than if you've hard-coded your "form" as a JFrame, then scrap it and re-do it as a JPanel.
I suggest:
Create an addEditBook modal JDialog
Give it getter methods to allow outside classes to be able to query its textfields for their contents.
Display the dialog from the main program.
Since it is modal the main program's code flow will pause until the dialog has been dealt with.
In your OK and Cancel button, set the dialog's state (OK_STATE or CANCEL_STATE) and close the dialog. The easiest way to do this actually is to use a JOptionPane as your modal dialog since it has mechanism for just this sort of thing. This is easily accomplished if your addEditBook is geared to create a JPanel, one that you display in the JOptionPane.
Program flow will then resume in your main program from right after where you showed the dialog
query the dialog for the contents of its fields.
For examples of the JOptionPane solutions, including option panes that request information from multiple fields similar to your window above, please see:
How can I make a JFrame modal like a JOptionPane?
Multiple input in JOptionPane.showInputDialog
Edit
You state in comment:
Oh and I was wondering how can I make the field of a normal JOptionpane input dialogue come up with a word already in it like for editing it will show the information stored already?
Please see the example answers that I have listed above as you'll see that they're not examples of a "normal JOptionPane" but rather JOptionPanes that display a GUI that you create. And just the same as it's easy to query the state of this GUI after it is displayed, it's just as easy to set the state of the GUI via setter methods before it is displayed.
My question is how can I get the information the user enters in the
text fields? Do I have to use something like getters, or is there an
easier way
You need to add actionListeners for you buttons, which means you will be overriding a method called actionPerformed. You basically need to associate your actionListeners with your 'Ok' and 'Cancel' buttons. When the 'ok' button is pressed, you should get a callback in the associated actionPerformed method. Then you should try to fetch the values of your textfiled using the getText method. Collect all the fileds and set the bean you have created to store that data. Then you can call your business logic to save/modify the books info.

How to trigger Java Swing InputVerifier on enter in JComboBox (actionPerformed)?

I have a Swing JComboBox with an InputVerifier set correctly.
I am using the combo box to set an integer.
If I type "cat" in the field and hit tab, my InputVerifier triggers and resets the value to "0".
If I type "cat" and hit enter, my InputVerifier is never called from actionPerformed. Do I need to explicitly call my InputVerifier from actionPerformed?
What's the best model to validate my JComboBox on tab and enter? It seems like this is something that should be given to me "for free" by the swing model.
The problem is "hit Tab" and "hit Enter" mean two different things in Java Swing. But those two actions mean the same thing to you, me, and the user.
Swing has no single mechanism to detect "when the user is done entering data". Instead, Swing focuses on the mechanics of "is this field losing keyboard focus" and "is the user pressing Enter key while inside a field".
Semantically those two actions mean the same thing from the user's perspective: "I'm done. Here's my input.". But, from what I can tell, Swing fails to offer a way to detect that user intention. I'm as surprised as you by the lack of such a feature, as this seems to be the most basic function of a form in a GUI. What we need, but don't have, is a "dataEntered" event.
There is a workaround…
In a similar context (JTextField instead of JComboBox) the Sun/Oracle Java Tutorial provides the example InputVerificationDemo where a class is created that:
Extends InputVerifier (to handle tabbing/clicking where focus is about to be lost)
Implements ActionListener (to handle pressing Enter key without leaving field)
The good thing about this workaround is that you can locate your handling code all in one place. The downside is that you still have the hassle of:
Creating a separate class.
Instantiating that class.
Passing that instance to both the setInputVerifier and addActionListener methods of your widget (JTextField, etc.).
This is the expected behavior of InputVerifier: the TAB key attempts to change focus, while the ENTER key does not. You can bind the ENTER key to a different action, as described in the tutorial How to Use Key Bindings. Also, consider the informative article Key Bindings, which includes a handy utility application.
When using an editable combo box, focus is on a JTextField which is used as the editor of the combo box. You can add an ActionListener to this text field.
In the ActionListener you could try invoking the transferFocus() method which should be equivalent to tabbing our of the text field. If that doesn't work then tha actionListener should invoke the same editing code as the InputVerifier.

JPanel not listening to key event when there is a child component with JButton on it

I'm working on a map editor for my college project. And I had a problem that the map panel is not listening key event while it should.
This happens when I add a ToolBarPane (which extends JPanel) with JComponent such as JButton, JComboBox that implements ActionListener on it AND the map panel (which extends the JPanel) together on to the Frame (I used BorderLayout). I have System.out.println statement to test if the key press is received, and it's not printing, if I remove the ToolBar, the key listener works again, so is the mouseListenner is disabled just like the keyListener, which means I can't handle press events etc, but the mouseListener works fine and I can still handle mouse move event.
Here is a screen shot how it works without the ToolBarPane
http://img684.imageshack.us/img684/3232/sampleku.png
note that you can use the mouse to put images on the map, you can also select images using the mouse just like a laser tool, and by pressing number key you can switch between different images, this works fine until I add the ToolBarPane which shows like this:
img291.imageshack.us/img291/8020/failve.png
(please add http before that, I can only post one hyperlink)
(I can't post images here because I'm a new user)
With the ToolBarPane on I was no longer able to handle the key event.
I guess it might by that the focus as been transferred to that panel somehow, but not sure at all.
Does and body know this and can help me out?
Thanks very much
I suggest you use the InputMap and WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or something similar. Excerpt from How to Use Key Bindings:
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
The component contains (or is) the component that has the focus. This input map is commonly used for a composite component
That has worked very robustly for me. Have a look at my other post for more information and actual code examples:
Keyboard input for a game in Java
or this tutorial:
Swing: Understanding Input/Action Maps
You should NOT be using a KeyListener.
Swing was designed to use Key Bindings which is far more flexible. Check out my quick summary of Key Bindings which also includes a link to the Swing tutorial which conains far more detail.
(I can't post images here because I'm a new user)
An image doesn't help much anyway. If you need more help post your SSCCE which shows the problem (after trying the above suggestion).

Categories