Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Key Listeners

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
0
0
Here is the problem:

I have a JPanel (Lets say Panel1) with some components on it, another JPanels, JTextBoxes, JComboBoxes,...

I need to make a JDialog appear when the user presses one of the Function buttons on the keyboard.
What listeners should I add to Panel1 to do this? Do I need to add this same listeners to all the components also?
What I need is that regardless where the focus is when I press a specific Function button this JDialog will appear. It seems stupid if I have to add listeners to all the components inside the panel since there are a lot of them.

Please give some detail about this subject.

Any help is apreciated.

Thank you all
 
You could write your own class which extends JPanel and implements KeyListener. Also it should override JPanel's add-method, and it that method you can assign every component you add an KeyListerner
ex.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class KeyPanel extends JPanel implements KeyListener {
public KeyPanel(){
super();
}
public void keyPressed(KeyEvent e){
if(e.getKeyChar()=='a')
System.out.println("test test test");
}
public void keyTyped(KeyEvent e){
}
public void keyReleased(KeyEvent e){
}
public Component add(Component comp){
super.add(comp);
comp.addKeyListener(this);
return comp;
}
}
it's just a test, but this is one way to do it.
 
yes yes that helped thank you

that will allways work I think, except if the focus is on the Panel??
But I think a JPanel can never have the focus right?
This sounds stupid... but it's just to confirm
 
As far as i know the JPanel can't get focus unless you set it yourself.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top