Java KeyListener is not working - java

I've just managed to get KeyListener to work in an empty application, but then I tried to implement it in my application and it simply doesn't work, no matter how much I enter keys!
A friend told me it's because I have buttons (JButton) on the application (and I implement the actionPerformed method,) can anyone explain to me why this is happening (and how to fix it) ?
EDIT:-
Yes, the problem is about focus, and I found the solution in some forums, and the solution is very simple. It`s by adding:
setFocusable(true); after, setVisible(true); in the class that extends JFrame.

To wich component are you adding the KeyListener? i think that if you want to listen the KeyEvents in the whole calculator you must add it to the Container in wich the buttons are.
But i belive that only the component who has the focus recive the KeyEvents, so that i dont know if the container can has the focus or if the events are promoted to their parent if the focus is on the buttons of the calculator.
You can solve this adding a keyListener to the container doing the stuff (printing the characters i suposse), and to the buttons and the textfield, promoting the event to it's container

Related

How to make JTextFields clickable?

I posted a similar question a year ago, but it was not really well written and I didn't get an answer I could work with. Now I stand in front of the same problem. I got a JPanel (my content pane), where a MouseListener is implemented.
Everywhere I click, I get the exact coordinates of my mouse click. Except my JTextField components. When I click on those, the MouseEvent isn't even triggered. H
ow do I do this, so my mouse clicks on those will also call the mouse event?
Tried: setEnable(false) and setHighlighter(null)
Sorry thought I fixed the X/Y problem.
The X/Y problem simply means you are telling us what your attempted solution is without telling us what your requirement is. We can't suggest a different approach if we don't know what you are trying to do.
I want to open a menu,
Now we know what the requirement is.
The solution is to add the MouseListener to the text field, not the panel. If you have the same popup of the panel and the text field, then you still need to add the listener to both the panel and the text field.
You can do this in one of two ways:
Read the section from the Swing tutorial on Bringing up a Popup Menu for a working example.
Note the above tutorial is a little old, you can also check out the setComonentPopuMenu(...) method of the JComponent class. This approach will create the listener for you.

How to change JPanel using KeyListener? [duplicate]

I am developing a game, where you first get to the main screen, there are multiple selections to go, for example, Singleplayer, Twoplayer, Credits, etc.
I have one big problem. If I click a button in the menu, (not JButton) the JPanels switch, but the keyListener is lost. The Keylistener is in the same class as the game code, which implements JPanel. I tried everything to get the Keylistener to work, but it just won't.
Here is how the things are called: Main class --> Menu --> Game. I tried adding the keylistener to the main class, but it's not working.
So, JPanel switching is ok, but the Keylisteners are gone. I was developing the game before with new JFrames, so when I clicked a menu, a new frame was created. I didn't insert a code here, because it's too long (2000+ lines), and the KeyListener is working, but only when it is in a new JFrame. I set the mode int in the Menu class, by clicking a button.
This is currently my panel switch:
public void setJPanel() {
switch (mode) {
case 1:
getContentPane().add(s);
validate();
break;
case 2:
getContentPane().removeAll();
getContentPane().add(sp);
validate();
break;
}
}
Thanks for your help in advance!
Rather than use a KeyListener, have you given thought to or tried using Key Bindings? KeyListeners require that the component being listened to has focus, and focus may be lost for many reasons, especially when swapping views (are you using a CardLayout for this?). Key Bindings on the other hand can be set to be responsive even if the bound component doesn't have focus but when it is only held within a window that has focus. Tutorial: Using a CardLayout
Edit
I see that you're not using a CardLayout, and I suggest that you use this as it can make your view swapping cleaner and easier.
Edit 2
I agree that you don't want to post your entire 2000+ line program here as no one will have the time to read it, but consider condensing your question/problem into a single small class that is compilable and runnable by any and all of us, and demonstrates your problem. In other words, a Short, Self Contained, Compilable, Example or SSCCE .
Remember, the code should be compilable and runnable for many of us to be able to understand it fully.
Cardlayout actually is screwy while refocusing.
#op, try calling requestFocusInWindow() after the new jpanel was added
Try using myPanel.requsetFocusInWindow();
before using setVisible(true);

Puzzle game with KeyListener using Java GUI?

I want to implement key listener on my puzzle game.
i have done it with action listener but now want to move on with key listener.
My logic for action listener was that:
when a specific button is clicked
it checks if is adjacent button's icon is null
if it is null then their icons will be swapped
Now, how can I do it with key listener?
Thank you.
if( b1==e.getSource()){
if(b2.getIcon()==null){
b2.setIcon(b1.getIcon());
b1.setIcon(null);
}
else if(b5.getIcon()==null){
b5.setIcon(b1.getIcon());
b1.setIcon(null);
}
}
You tell us that you have implemented a KeyListener but it's not working. Without code, all we can do is guess, so here's mine:
KeyListeners require focus to work, and so if your GUI has any components that steal the focus, such as JButtons, all JTextComponents such as JTextArea or JTextField, JComboBoxes, JLists,... then your KeyListener won't work.
One kludge is to force the component with the KeyListener to have the focus and to greedily hold on to the focus. This is not advisable since it will force your program to behave abnormally since most users expect buttons to have and retain focus when pressed, and text components won't work if they're not allowed focus.
Again, often the best solution is to use Key Bindings since these can work without requiring focus and are a cleaner way to capture keystrokes. Please look at the Key Bindings Tutorial and then have a look at my example code for using Key Bindings here and here.
Again for better and more specific help, then please tell us more of the details and show us your pertinent code, preferably as a minimal example program or MCVE.

Java keyListener with multiple JPanel

I'm having a problem with Java KeyListener when adding adding another JPanel with 5 JLabels, I've searched around this website, and most solutions to this problem involve switching from KeyListener to KeyBindings. This wont work for me because I need to know exactly when a key is pressed, released and held down. To my knowledge, KeyBindings does not provide all those.
I've tried to use
this.requestFocus();
after creating the new JPanel, but it didn't work, however when I use the same line inside the paintComponent(), it works. Which brings me to my questions: How does this reflect on performance? My paintComponent() is called about 60 times/sec. Is there a way to call it once and still have this working? I see that requestDefaultFocus() from the type JComponent is deprecated...
I've also tried adding same KeyListener to the second JPanel, but that didn't help. Im guessing one of the JLabels is the one that gets focus?
This wont work for me because I need to know exactly when a key is pressed, released and held down. To my knowledge, KeyBindings does not provide all those.
Yes it does. You have an Action for "pressed" and "released". There is no such Action as "held down" (even for a KeyListener), you just get multiple events generated.
this.requestFocus();
That is not the proper method to use for requestion focus on a component. Read the API for that method and it will tell you the proper method to use.
however when I use the same line inside the paintComponent(), it works.
This is because you can't request focus on a component until the frame has been realized, which means you've invoked pack() or setVisible() on the frame.
Is there a way to call it once and still have this working?
See the RequestFocusListener class in Dialog Focus.
The proper solution is to use Key Bindings so you don't need to use these work arounds.

Can't edit any component in GUI

I came up with a recently problem that, any component that I add to a JPanel (JTextField, JTextArea, JTable) can't edit even when I force it, in code, to be enabled and editable. I'm using NetBeans for developing the project.
Anyone here faced this problem? Looks like I'll be forced to change all to JFrame. Even though, hope that someone reply this topic with some constructive idea/help.
Try to call setFocusable(true) for the top level container.
I have two reasons/opinions/thoughts as to why you are getting "errors".
You aren't adding the components to the panel correctly.
panel.add(someComponent);
panel.add(anotherComponent);
panel.add(yetAnotherComponent);
frame.add(panel);
You are overriding the default behavior for the components. All components in a JFrame, JWindow, etc. are by default enabled and editable (meaning there is an implied setEnabled(true) and setEditable(true), respectively).

Categories