KeyListener HELP
PLEASE lol Iv tried to get this to work for about 6 months now. Iv finaly broken down to post here PLEASE help. Basicaly the KeyListener is not working at all. It should print out "Key Was" whenever there is ANY key action but it doesnt.
Below is the code to my java program. It can be used as is and doesnt need any otehr classes or files. I have stripped it down to the basic shell and got rid of all pictures, cursors, sounds, etc AND the most of teh sorce code to go with these to make it easy. I may have left in some of teh variable names however lol so just ignore them. Again please help and I will be eternaly greatful.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.midi.*;
import javax.sound.sampled.*;
import java.util.*;
import java.io.*;
class space extends JComponent {
private static DisplayMode[] BEST_DISPLAY_MODES = new DisplayMode[] {
new DisplayMode(800, 600, 32, 0),
new DisplayMode(800, 600, 16, 0),
new DisplayMode(800, 600, 8, 0)
};
String file = "save";
String CustomIcon = "icon.gif";
Frame frame;
thescreen drawPanel;
Window win;
Image Cimage;
Cursor c;
Toolkit tk;
Point Cpoint;
int MouseXp;
int MouseYp;
int MouseXm;
int MouseYm;
String menubg = "space.jpeg";
int menuselect = 0;
ArrayList profilenames = new ArrayList();
int listnum = 0;
boolean ExitSelect = false;
boolean SPlayerSelect = false;
boolean BackSelect = false;
boolean NewOfficerSelect = false;
boolean NameKey = false;
Sequence sequenceMbg;
Sequencer sequencerMbg;
String music = "SC1.mid";
Sequence sequenceB;
Sequencer sequencerB;
String beep = "beep.wav";
GraphicsEnvironment ge;
GraphicsDevice gs;
public static void main(String args []){
space gui = new space();
gui.go();
}
public void go(){
MouseXp = 0;
MouseYp = 0;
MouseXm = 0;
MouseYm = 0;
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gs = ge.getDefaultScreenDevice();
if (gs.isFullScreenSupported()) {
} else {
}
frame = new Frame(gs.getDefaultConfiguration());
drawPanel = new thescreen();
win = new Window(frame);
win.add(drawPanel, BorderLayout.CENTER);
try {
gs.setFullScreenWindow(win);
win.validate();
if (gs.isDisplayChangeSupported()) {
chooseBestDisplayMode(gs);
}
} finally {
}
frame.setFocusable(true);
win.setFocusable(true);
MyKeyListener customKeyListener = new MyKeyListener();
win.addKeyListener (customKeyListener);
mouselis custommouselis = new mouselis();
win.addMouseListener(custommouselis);
win.addMouseMotionListener(custommouselis);
menuselect = 1;
drawPanel.repaint();
}
class thescreen extends JPanel {
public void paintComponent (Graphics g){
if(menuselect == 0){
g.setColor(Color.black);
g.fillRect(0,0,800,600);
}
if(menuselect == 1){
g.setColor(Color.black);
g.fillRect(0,0,800,600);
g.setColor(Color.green);
g.drawString(MouseXm + ", " + MouseYm, 40, 40);
g.drawString(MouseXp + ", " + MouseYp, 40, 70);
Font font = new Font("Ariel", Font.BOLD, 30);
g.setFont(font);
if(ExitSelect){
g.setColor(Color.orange);
}
g.drawString("EXIT", 650, 450);
g.setColor(Color.green);
if(SPlayerSelect){
g.setColor(Color.orange);
}
g.drawString("Single Player", 200, 100);
g.setColor(Color.green);
}
g.dispose();
}
}
private static DisplayMode getBestDisplayMode(GraphicsDevice device) {
for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
DisplayMode[] modes = device.getDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes.getWidth() == BEST_DISPLAY_MODES[x].getWidth()
&& modes.getHeight() == BEST_DISPLAY_MODES[x].getHeight()
&& modes.getBitDepth() == BEST_DISPLAY_MODES[x].getBitDepth()) {
return BEST_DISPLAY_MODES[x];
}
}
}
return null;
}
public void selectfalse(){
ExitSelect = false;
SPlayerSelect = false;
BackSelect = false;
}
public static void chooseBestDisplayMode(GraphicsDevice device) {
DisplayMode best = getBestDisplayMode(device);
if (best != null) {
device.setDisplayMode(best);
}
}
class mouselis implements MouseListener, MouseMotionListener{
public void mousePressed (MouseEvent me){
MouseXp = me.getX();
MouseYp = me.getY();
if(menuselect == 1){
if(MouseXp > 645 && MouseXp < 735 && MouseYp > 420 && MouseYp < 455){
win.dispose();
gs.setFullScreenWindow(null);
System.exit(0);
}
if(MouseXm > 195 && MouseXm < 360 && MouseYm > 70 && MouseYm < 115){
selectfalse();
}
}
repaint();
drawPanel.repaint();
frame.repaint();
}
public void mouseReleased (MouseEvent me){
}
public void mouseExited (MouseEvent me){
}
public void mouseEntered (MouseEvent me){
}
public void mouseClicked (MouseEvent me){
}
public void mouseMoved (MouseEvent me){
MouseXm = me.getX();
MouseYm = me.getY();
if(menuselect == 1){
if(MouseXm > 645 && MouseXm < 735 && MouseYm > 420 && MouseYm < 455){
ExitSelect = true;
}else{
ExitSelect = false;
}
if(MouseXm > 195 && MouseXm < 360 && MouseYm > 70 && MouseYm < 115){
SPlayerSelect = true;
}else{
SPlayerSelect = false;
}
}
repaint();
drawPanel.repaint();
frame.repaint();
}
public void mouseDragged (MouseEvent me){
mouseMoved(me);
}
}
class MyKeyListener implements KeyListener{
public void keyPressed (KeyEvent event){
System.out.print("Key was Pressed");
}
public void keyReleased(KeyEvent event){
System.out.print("Key was Released");
}
public void keyTyped(KeyEvent event){
System.out.print("Key was Typed");
}
}
}
[6536 byte] By [
CptDavidJr] at [2007-9-30 21:21:19]

Try requesting focus in the component that you are listening for key events. For example:Frame f = new Frame();//the following line should be one of the last lines in the methodf.requestFocus();
didnt work :-/anything else? Or even any ideas of where ELSE to ask? lol...
FORMAT you code peoble, formaaaat!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.sound.midi.*;
import javax.sound.sampled.*;
import java.util.*;
import java.io.*;
class space extends JComponent {
private static DisplayMode[] BEST_DISPLAY_MODES = new DisplayMode[] {
new DisplayMode(800, 600, 32, 0),
new DisplayMode(800, 600, 16, 0),
new DisplayMode(800, 600, 8, 0)
};
String file = "save";
String CustomIcon = "icon.gif";
Frame frame;
thescreen drawPanel;
Window win;
Image Cimage;
Cursor c;
Toolkit tk;
Point Cpoint;
int MouseXp;
int MouseYp;
int MouseXm;
int MouseYm;
String menubg = "space.jpeg";
int menuselect = 0;
ArrayList profilenames = new ArrayList();
int listnum = 0;
boolean ExitSelect = false;
boolean SPlayerSelect = false;
boolean BackSelect = false;
boolean NewOfficerSelect = false;
boolean NameKey = false;
Sequence sequenceMbg;
Sequencer sequencerMbg;
String music = "SC1.mid";
Sequence sequenceB;
Sequencer sequencerB;
String beep = "beep.wav";
GraphicsEnvironment ge;
GraphicsDevice gs;
public static void main(String args []){
space gui = new space();
gui.go();
}
public void go(){
MouseXp = 0;
MouseYp = 0;
MouseXm = 0;
MouseYm = 0;
ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
gs = ge.getDefaultScreenDevice();
if (gs.isFullScreenSupported()) {
} else {
}
frame = new Frame(gs.getDefaultConfiguration());
drawPanel = new thescreen();
win = new Window(frame);
win.add(drawPanel, BorderLayout.CENTER);
try {
gs.setFullScreenWindow(win);
win.validate();
if (gs.isDisplayChangeSupported()) {
chooseBestDisplayMode(gs);
}
} finally {
}
frame.setFocusable(true);
win.setFocusable(true);
MyKeyListener customKeyListener = new MyKeyListener();
win.addKeyListener (customKeyListener);
mouselis custommouselis = new mouselis();
win.addMouseListener(custommouselis);
win.addMouseMotionListener(custommouselis);
menuselect = 1;
drawPanel.repaint();
}
class thescreen extends JPanel {
public void paintComponent (Graphics g){
if(menuselect == 0){
g.setColor(Color.black);
g.fillRect(0,0,800,600);
}
if(menuselect == 1){
g.setColor(Color.black);
g.fillRect(0,0,800,600);
g.setColor(Color.green);
g.drawString(MouseXm + ", " + MouseYm, 40, 40);
g.drawString(MouseXp + ", " + MouseYp, 40, 70);
Font font = new Font("Ariel", Font.BOLD, 30);
g.setFont(font);
if(ExitSelect){
g.setColor(Color.orange);
}
g.drawString("EXIT", 650, 450);
g.setColor(Color.green);
if(SPlayerSelect){
g.setColor(Color.orange);
}
g.drawString("Single Player", 200, 100);
g.setColor(Color.green);
}
g.dispose();
}
}
private static DisplayMode getBestDisplayMode(GraphicsDevice device) {
for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
DisplayMode[] modes = device.getDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes.getWidth() == BEST_DISPLAY_MODES[x].getWidth()
&& modes.getHeight() == BEST_DISPLAY_MODES[x].getHeight()
&& modes.getBitDepth() == BEST_DISPLAY_MODES[x].getBitDepth()) {
return BEST_DISPLAY_MODES[x];
}
}
}
return null;
}
public void selectfalse(){
ExitSelect = false;
SPlayerSelect = false;
BackSelect = false;
}
public static void chooseBestDisplayMode(GraphicsDevice device) {
DisplayMode best = getBestDisplayMode(device);
if (best != null) {
device.setDisplayMode(best);
}
}
class mouselis implements MouseListener, MouseMotionListener{
public void mousePressed (MouseEvent me){
MouseXp = me.getX();
MouseYp = me.getY();
if(menuselect == 1){
if(MouseXp > 645 && MouseXp < 735 && MouseYp > 420 && MouseYp < 455){
win.dispose();
gs.setFullScreenWindow(null);
System.exit(0);
}
if(MouseXm > 195 && MouseXm < 360 && MouseYm > 70 && MouseYm < 115){
selectfalse();
}
}
repaint();
drawPanel.repaint();
frame.repaint();
}
public void mouseReleased (MouseEvent me){
}
public void mouseExited (MouseEvent me){
}
public void mouseEntered (MouseEvent me){
}
public void mouseClicked (MouseEvent me){
}
public void mouseMoved (MouseEvent me){
MouseXm = me.getX();
MouseYm = me.getY();
if(menuselect == 1){
if(MouseXm > 645 && MouseXm < 735 && MouseYm > 420 && MouseYm < 455){
ExitSelect = true;
}else{
ExitSelect = false;
}
if(MouseXm > 195 && MouseXm < 360 && MouseYm > 70 && MouseYm < 115){
SPlayerSelect = true;
}else{
SPlayerSelect = false;
}
}
repaint();
drawPanel.repaint();
frame.repaint();
}
public void mouseDragged (MouseEvent me){
mouseMoved(me);
}
}
class MyKeyListener implements KeyListener{
public void keyPressed (KeyEvent event){
System.out.print("Key was Pressed");
}
public void keyReleased(KeyEvent event){
System.out.print("Key was Released");
}
public void keyTyped(KeyEvent event){
System.out.print("Key was Typed");
}
}
}
set the listeners to the component on which you wanna use them, actually added components already will register the listeners, but sometime it doesn't work, try to register the listeners on drawPanel
drawPanel.addKeyListener (customKeyListener);
drawPanel.addMouseListener(custommouselis);
drawPanel.addMouseMotionListener(custommouselis);
Hope it helps, goodLuck
Regards,
Mohammed Saleem
Hi!
I just posted a similar reply to someone looking for an explanation of the enhanced for loop. The documentation you seek is in the JDK docs -- from the main index page, link to Swing in the big image at the top. Then look for "The AWT Focus Subsystem" which will explain how to install the appropriate handler.
Later!
- Coco.
I tried doing it to the drawpanel before and it didnt work.Nice try though lol thx.About the JDK docs, do you have a link to that exact one? lol
http://java.sun.com/docs/books/tutorial/uiswing/index.html
Hi! (-- This is "java@stevencoco.com");
I'm glad you replied again -- my previous post was a little confusing -- I replied about the JDK docs.
The actual one I referred to (the focus subsystem) is at:
http://java.sun.com/j2se/1.5.0/docs/api/java/awt/doc-files/FocusSpec.html
The main index page is:
http://java.sun.com/j2se/1.5.0/docs/index.html
It's also in the JDK doc bundle that you download. The reason I mentioned it before was that there is A L-L-L-L-L- LOT of documentation in that bundle! I said once: the Complete Instruction COURSE!!!!!!
This is some of the most useful documentation/information you can find in Java.
The above doc should explain how to dynamically obtain a line to listen on events from the appropriate key source to consume these events and do what you are trying to do!!!!! In other words, you should be able to write one listener, and add it to the appropriate method such that no matter what you stuff into your GUI, your listener will consume the necessary KeyEvents.
Good luck!!!!!!!!!!
- Coco.
lol I studied and studied those docs but I STILL cant get this to work! lol any more sugestions?
OK. Here is a working draft -- Note: You must read the documentation to fully undrstand what the scope of this global listener really will be, as well as the required contract for its behavior. The URL; in the docs I mentioned before; is: http://java.sun.com/j2se/1.5.0/docs/api/java/awt/doc-files/FocusSpec.html Look into the KeyEventDispatcher implementation. But this also plays into the focus subsystem implementation itself -- as to what the scope will be (and so which components will not exhibit the desirable behavior this test case shows) so that your program does not wind up broken!!!
Here is the executable:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
/**
* Requires JRE 5.0!
*/
public class Main {
public static void main(String[] args) {
/* Junk -- create 2 frames filled with stuff to grab the focus: */
final JFrame frame = new JFrame("Focus Test");
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("South"), BorderLayout.SOUTH);
JPanel panel = new JPanel(new FlowLayout());
frame.add(panel, BorderLayout.CENTER);
panel.add(new JTextField("Center 1"));
panel.add(new JTextField("Center 2"));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.setVisible(true);
}
});
final JFrame frame2 = new JFrame("Focus Test 2");
frame2.setLayout(new BorderLayout());
frame2.add(new JButton("North"), BorderLayout.NORTH);
frame2.add(new JButton("West"), BorderLayout.WEST);
frame2.add(new JButton("East"), BorderLayout.EAST);
frame2.add(new JButton("South"), BorderLayout.SOUTH);
JPanel panel2 = new JPanel(new FlowLayout());
frame2.add(panel2, BorderLayout.CENTER);
panel2.add(new JTextField("Center 1"));
panel2.add(new JTextField("Center 2"));
frame2.pack();
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLocation(frame.getLocation().x + frame.getSize().width,
frame.getLocation().y);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame2.setVisible(true);
}
});
System.out.println();
System.out.println();
/*
* This is the code that attempts to answer your question:
* This IS A HALF-BAKED ATTEMPT (NB!!) At installing a global
* keyListener:
*/
KeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
System.out.println("Key was: " + e.getKeyChar());
return false;
}
});
}
}
You can click different buttons to move the focus around -- even switch frames and also type in the textfields and all the events are trapped.
Getting closer?
- Steev.
interesting... well ill play around with it lol. thx :)