Global key listener
Hi,
I currently implemented a keylistener using extending key adapter which uses keypressed to listen on what key is pressed.
It works good. However, when ever I click on a Swing input control like Jtextfield the "hotkey" is no longer functional. But it still works if i click on non-input controls like jlabels.
is there a better way in creating a hotkey function in java which overrides, so is still functional even if I click on a Jtextfield ?
Thanks
Have you tried using KeyBindings instead of a key listener or adapter?
for instance
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
public class FuSwing
private static final String CONTROL_U = "Ctrl-U";
private JPanel mainPanel = new JPanel();
public FuSwing()
mainPanel.setPreferredSize(new Dimension(400, 400));
mainPanel.add(new JButton("Foo"));
JTextField field = new JTextField(12);
mainPanel.add(field);
putAction(mainPanel, KeyEvent.VK_U, CONTROL_U, ActionEvent.CTRL_MASK);
//removeAction(field, KeyEvent.VK_U, CONTROL_U, ActionEvent.CTRL_MASK);
private void putAction(JComponent comp, int keystroke, String keyString, int mask)
KeyStroke ks = KeyStroke.getKeyStroke(keystroke, mask);
comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, keyString);
comp.getActionMap().put(keyString, new KeyAction(keyString));
private void removeAction(JComponent comp, int keystroke, String keyString, int mask)
KeyStroke ks = KeyStroke.getKeyStroke(keystroke, mask);
InputMap im = comp.getInputMap(JComponent.WHEN_FOCUSED);
im.put(ks, "none");
private class KeyAction extends AbstractAction
private String keyStr = "";
public KeyAction(String keyStr)
this.keyStr = keyStr;
@Override
public void actionPerformed(ActionEvent e)
if (keyStr.equals(CONTROL_U))
System.out.println("Control U pressed");
public JPanel getMainPanel()
return mainPanel;
private static void createAndShowUI()
JFrame frame = new JFrame("FuSwing");
frame.getContentPane().add(new FuSwing().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
createAndShowUI();
}
Similar Messages
-
I'm trying to use global keys hooking but why it's never get to the events ?
I created a new class and added this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Capture
class Hook_Keys
globalKeyboardHook gkh = new globalKeyboardHook();
public bool onoff = false;
public Hook_Keys()
gkh.HookedKeys.Add(Keys.A);
gkh.HookedKeys.Add(Keys.B);
gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
void gkh_KeyUp(object sender, KeyEventArgs e)
onoff = true;
e.Handled = true;
void gkh_KeyDown(object sender, KeyEventArgs e)
onoff = false;
e.Handled = true;
Then in another class top i added:
Hook_Keys hookeys = new Hook_Keys();
And then using it like this:
if (hookeys.onoff == true)
font.DrawText(null, String.Format("{0:N0} fps", this.FPS.GetFPS()), 5, 5, SharpDX.Color.Red);
string timeRunning = FramesPerSecond.RunTime.ToString();
font.DrawText(null, String.Format("{0:N0} time running ", timeRunning), 5, 30, SharpDX.Color.Red);
But when i click on A or B i used a breakpoint it's never get in to the events gkh_KeyUp and gkh_KeyDown
I used a breakpoint and it does doing the constructor the public Hook_Keys() part.
But never get to the events.
I took the code from here:
Global Key Hook
What i want to do is either clicking on A or B one of them will change the bool variable to true and the other key to false.Try to add the below in your form constructor:
public Form1()
InitializeComponent();
KeyPreview = true;
Fouad Roumieh -
Error when loading wsdl"No global key defined"
Hi Experts,
I am working on a IDOC -Web Service scenario.The wsdl provided from the destination has been uploaded as a External definition.When I add it to the mapping part, I get an error saying that "No global key defined".
Please suggest on this.
Thanks,
TinyHi
Answer is pure assumption
Pls check the OSS note.
Note 1097012 - External def. corrupt after transfer to Integration Rep.
Take opinion from SAP / Basis before implementing the OSS note
Regards
Madhan D
Edited by: Madhan Doraikannan on Mar 25, 2009 11:19 AM -
LISTENING FOR BACKSPACE WITH A KEY LISTENER
I have a key listener and I want to know how I find out if backspace has been pressed.
ThanksI created a JTextField and added it to a JPanel which was added to the contentPane.
When I add my key listener to a JTextField or the the JFrame, the code suggested above works fine. (JKD1.3, Windows 98)
When I add the key listener to the JPanel it doesn't work. -
How can I add the key listener to JFrame
Hi,
How can I add the Key Listener to the JFrame? I want to show the Windows default popup which comes after right clicking on the frame's header. I want to add the key board support for the same1. Make sure that key events are enabled on your component. (AWTMulticaster.enableEvents(...)
2. add the keylistener -
PI7.1 error: no global key defined
Hi Experts,
I am getting an error when trying to open a message mapping in PI7.1: no global key defined. What does that mean? Can anyone shed some light on this? I've been unsuccessful in searching this error in SDN.
Regards,Hi Sugata,
The solution provided by you is working in case we have XSD that are not having External References. However, when we tested the solution provided by you in one of the scenario where we have several XSDs referring each other, It does not work.
Also, we have found the link: http://wiki.sdn.sap.com/wiki/display/XI/ConvertingXSDtoSAP-PIcompatible+XSD
Thanks & Regards
Varun Goel -
I have put a key listener in a JTextField, but when I hit the tab key it does not generate a keyPressed event. Currently tab does nothing not even cycle through GUI components. Can you help me figure ouy how to get it to recognize the tab key.
P.S. The code that is inside the tab block works as I tried it with other keys so that is not the error.I would search the forums for jtextfield and tab in the title
http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Btitle%3Ajtextfield+%2Btitle%3Atab&col=javaforums -
Air Native Extension - Java Key Listener
Hello all,
Firstly I'd like to thank you for creating an excellent and helpful community. I have an issue I have been stuck on for around 2 weeks now.
I am creating an android native extension to listen to key input from a proprietary remote control device. GameInput does not recognise it as a game controller so we have to create a native extension to get the input. I have it working fully except for one issue; if the game loses context (eg the user gets a phone call or the game goes into the background for any other reason) I do not get any other input.
The way I am doing it is to attach an onKeyListener to the currently focused View (an AirWindowSurfaceView). This works perfectly, but when the context is lost I'm assuming the AirWindowSurfaceView changes and I cannot find a way to get a reference to the new one. Here is my key listener setup code (from the native Java):
public void updateListeners()
if(_view != null)
_view.setOnKeyListener(null); //remove from the old view
_view.setOnGenericMotionListener(null);
_context.dispatchStatusEventAsync(_view.toString(), "view"); //send the current view details
_view = _context.getActivity().getCurrentFocus(); //set the new view
_context.dispatchStatusEventAsync(_view.toString(), "view");
if(_onKeyListener == null)
_onKeyListener = new NativeGamepadKeyListener(_context, this); //create new key listener
if(_onGenericMotionListener == null)
_onGenericMotionListener = new NativeGamepadMotionListener(_context, this); //create a new motion listener
_view.setOnKeyListener(_onKeyListener); //set on the new view
_view.setOnGenericMotionListener(_onGenericMotionListener);
This updateListeners function is called when I get a focus change event on the current view (attached in a similar way) but this doesn't seem to keep it up to date with the current View.
Please note I'm a newbie at making extensions like these and might be going about it totally the wrong way - if I am and you have any suggestions as to the best way to use an onKeyListener in a native extension I'd love to hear it.
Thanks in advance for your help!I am not able to solve this yet. Is anybody else facing this this problem.
-
Remove the key listener from JTable problem please help
Hi
I�m trying to remove the key listener from my table, it doesn�t work,
I�m pressing the enter key it still goes to the next row from the table,
hear is my code
KeyListener[] mls = (KeyListener[])(table.getListeners(KeyListener.class));
for(int i = 0; i < mls.length; i++ )
table.removeKeyListener(mls);
Please help thanksHm ...
that should indeed remove all the KeyListeners from your table - the question is only, when does this happen?- Where in your code do you remove the KeyListeners?- I am quite sure, you remove them successfully, but after your have removed them, one or more KeyListeners are added to the table.
greetings Marsian -
Hi all:
I'm trying to write a filterable jtable. User can input the filter rule in the table header and the table displays the filtered data at the same time when the user inputs letters. The table filter works fine. But when I try to add "TAB" key listener, I find that I can't track the "TAB" key. I use a customerized cell renderer to display the filterable table header, a customerized cell editor to edit the filterable table header. The cell editor is created like this:
JTextField textField = new JTextField("");
DefaultCellEditor cellEditor = new DefaultCellEditor(textField);
And I add a KeyListener to the textField. The KeyListener can track other keys like "Shift", "Alt", "Ctrl", but it can't track "TAB". It's weird. I also add the KeyListener to JTableHeader, JTable, but when I edit something in the JTextField, I still can't catch the "TAB" key. Have any ideas? Thank you for your time.by default the Tab is used (and consumed) by
focusManager to move focus between components. If you
want to get it in a component you have to signal the
manager to keep it's hands off. How to do so depends
on the jdk version. Focus handling changed
considerably between 1.3 and 1.4: Prior to 1.4 you
have to subclass the component in question to return
true on isManagingFocus(), since 1.4 you have to set
the comp's focusTraversalKeys to make the manager take
those instead of the default keys.
Greetings
JeanetteThanks Jeanette, it works. I use the Component.setFocusTraversalKeysEnabled(false) to disable all traversal keys of JTextField and add a KeyEventDispatcher to the KeyboardFocusManager. It finally works. Users can use "TAB" keyStroke and "Shift-TAB" keyStroke to traverse in the filterable table header now. Thank you for your great help and the $$ are yours. -
Hello
I m writing a key listener to change label 1 to blue when the one key is pressed and change to grey when another key is pressed. Here is my code for it so far.
if (evt.getKeyChar() == '1') {
process(evt.getKeyChar(lbl1.background = 51,255,255));
else if (evt.getKeyChar() != '1'){
process(evt.getKeyChar(lbl1.background = 240,240,240));
The second line starting with process to change the label colour does not function correctly but the first one does which gets the character. The label is a swing label but would it be best to change the label to a awt label to get the colour change to work using java.awt.colour? Also could I take out the .background part and just have lbl1= 51,255,255,255. Thanks ahead for any help with the second line.
NickNUFCjavaworker wrote:
Cheers for the help however it has made another problem. The shorter version worked the best so that is what I used. I implemented it like this:
public class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
lbl1.setBackground(evt.getKeyChar() == '1' ? Color.BLUE : Color.GRAY);
lbl2.setBackground(evt.getKeyChar() == '2' ? Color.BLUE : Color.GRAY);
lbl3.setBackground(evt.getKeyChar() == '3' ? Color.BLUE : Color.GRAY);
lbl4.setBackground(evt.getKeyChar() == '4' ? Color.BLUE : Color.GRAY);
lbl5.setBackground(evt.getKeyChar() == '5' ? Color.BLUE : Color.GRAY);
It went on like that until I had cover all the characters and all the labels, I wanted to cover. Here is the problem that occured. The code that is generated when you create a java desktop application using the latest version of netbeans now has errors in it. Do I have to import any other java events or items that will solve this problem.
NickErrors you say? -
Key listener problem while using jdk1.4
Hello All ,
i have a panel which is having two JTextFields and two JButtons .
I have added the key listener for the panel and trap the Esc button pressed and on this event i am making the panel invisible
This stuff was working prefectly fine with jdk1.3 but it is not working with the jdk1.4
any reasons ..
please reply ..
thanks
ssk_pUse JFrame instead of Panel and compliled by jdk1.4.
There are some changes for jdk1.4. A application compiled by jdk1.3 might not work properply for jdk1.4, especially for key listener. -
How to debug this key listener
how would I figure out what this key listener is actually doing, if anything?
piece1 is a new piece object that has a center at certain part on a matrix, with its width being at startPlaceX.
What I think should happened here is that when the user presses the left arrow key, it calls moveXLeft, which in turn, decrements the spot on the matrix that the current piece is.
In otherwords, how can I tell that the keyListener is doing anything? I have a function in my actionListener
public void startAnimation()
if (animationTimer == null)
animationTimer = new Timer(ANIMATION_DELAY, new TimerHandler());
animationTimer.start();
else
if (!animationTimer.isRunning())
animationTimer.restart();
public class TimerHandler implements ActionListener
public void actionPerformed(ActionEvent actionEvent)
piece1.moveDown(board);
piece1.drawIt(board, true);
repaint();
public void moveDown(int[][]board)
//startPlaceY++;
startPlaceY++;that works (IE, every given interval, it moves the specified piece down by 1)
here is the code in question
public void moveXLeft(int [][]temp)
startPlaceX--;
//startPlaceY+= change;
public class KeyHandler implements KeyListener
public void keyPressed(KeyEvent event)
switch (event.getKeyCode())
case KeyEvent.VK_LEFT:
piece1.moveXLeft(board);
//x -= size;
break;
case KeyEvent.VK_RIGHT:
piece1.moveXRight(-1);
//x += size;
break;
repaint();
public void keyReleased(KeyEvent event) {}
public void keyTyped(KeyEvent event) {}
}if you need any more info, please say so.
Edited by: thenextbesthang on Dec 16, 2007 12:33 PM
Edited by: thenextbesthang on Dec 16, 2007 12:33 PMheres the whole of my code (right now)
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
import java.awt.font.* ;
import java.awt.geom.* ;
public class project3{
public static void main(String[] args)
JFrame window = new JFrame();
window.setTitle("Tetris");
commenceGame begin = new commenceGame();
begin.init();
begin.startAnimation();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().add(begin);
window.pack();
window.setVisible( true );
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Pieces{
public int x;
public int y;
public int cross[][] = {{1,1,1},
{0,1,0}};
private int leftL[][] = {{2,2,2},
{2,0,0}};
private int rightL[][] = {{3,3,3},
{0,0,3}};
private int leftS[][] = {{0,4,4},
{4,4,0}};
private int rightS[][] = {{5,5,0},
{0,5,5}};
private int square[][] = {{6,6},
{6,6}};
private int tetris[][]= {{7,7,7,7}};
private int blankSquare[][] ={{0}};
public int startPlaceY;
public int startPlaceX;
public int shape;
public int replacement_board[][];
public Pieces()
x = 0;
y = 1;
startPlaceX = 4;
startPlaceY = 0;
shape = (int)(Math.random()*7);
replacement_board = new int[20][10];
public int[][] drawIt(int[][]temp2_board, boolean por)
//1
//temp2_board = replacement_board;
makeTetris(temp2_board);
//if(por) makeCross(temp2_board);//2
// temp2_board = replacement_board;
// else reMakeCross(replacement_board);
/* switch(shape)
case 0:
makeCross(temp2_board);
break;
case 1:
makeLeftL(temp2_board);
break;
case 2:
makeRightL(temp2_board);
break;
case 3:
makeLeftS(temp2_board);
break;
case 4:
makeRightS(temp2_board);
break;
case 5:
makeSquare(temp2_board);
break;
case 6:
makeTetris(temp2_board);
break;
return temp2_board;
public int[][] makeCross(int[][]temp)
replacement_board= temp;
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<2;i++)
for(int j = 0;j<3;j++)
color = cross[i][j];
temp[startPlaceX+i][startPlaceY+j] = color;
return(temp);
//this method is designed to take the initial condition and create the new matrix
public int[][] makeLeftL(int[][]temp)
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<2;i++)
for(int j = 0;j<3;j++)
color = leftL[i][j];
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public int[][] makeRightL(int[][]temp)
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<2;i++)
for(int j = 0;j<3;j++)
color = rightL[i][j];
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public int[][] makeLeftS(int[][]temp)
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<2;i++)
for(int j = 0;j<3;j++)
color = leftS[i][j];
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public int[][] makeRightS(int[][]temp)
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<2;i++)
for(int j = 0;j<3;j++)
color = rightS[i][j];
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public int[][] makeSquare(int[][]temp)
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<2;i++)
for(int j = 0;j<2;j++)
color = square[i][j];
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public int[][] makeTetris(int[][]temp)
for(int i=0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
temp[i][j] = 0;
int color;
for(int i = 0;i<4;i++)
for(int j = 0;j<1;j++)
color = tetris[j];
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public int[][] makeBlankSquare(int[][]temp, boolean check)
int color;
for(int i = 0;i<1;i++)
for(int j = 0;j<1;j++)
if(check) color = blankSquare[i][j];
else color = 0;
temp[startPlaceX+i][startPlaceY+j] = color;
return temp;
public void moveDown(int[][]board)
//startPlaceY++;
startPlaceY++;
replacement_board = board;
System.out.println(startPlaceY);
//temp[startPlaceX+i][startPlaceY+j] = color;
replacement_board = board;
if(board[startPlaceY][startPlaceX] &&
board[startPlaceY+1][startPlaceX] &&
board[startPlaceY-1][startPlaceX] &&
board[startPlaceY][startPlaceX+1] &&
board[i][j]==1) board[i][j]=0;
for(int i=0;i<board.length;i++)
for(int j = 0;j<board[0].length;j++)
System.out.print(board[i][j] + " ");
System.out.println();
System.out.println();
//System.out.println(startPlaceY);
//makeCross(board);
//return replacement_board;
public void moveXLeft(int [][]temp)
startPlaceX--;
//startPlaceY+= change;
public void moveXRight(int [][]temp)
startPlaceX++;
makeCross(replacement_board);
//startPlaceY+= change;
public int[][] killLiving(int[][]temp)
for(int i = 0;i<temp.length;i++)
for(int j = 0;j<temp[0].length;j++)
if(temp[i][j]!= 0)
temp[i][j] = -1;
return temp;
} import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class commenceGame extends JPanel
public int x;//starting x location of block
public int y;//starting y location of block
public int width;//width of block
public int height;//height of block
public int board[][];
/*{{-1,-1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1},
{-1,-1, -1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1}};//game play board*/
public int temp_storage_board[][];
public int xBoard;//width of board matrix
public int yBoard;//height of board matrix
public Timer animationTimer;
public int ANIMATION_DELAY;
Pieces piece1;//the piece that gets modified
Pieces piece2;//the piece that is the result of the modification
public commenceGame()
xBoard = 10;
yBoard = 20;
width = 20;
height = 20;
x = 5;
y = 0;
board = new int[yBoard][xBoard];
//this is the board where pieces appear
temp_storage_board = new int[yBoard][xBoard];//this is the main board
piece1 = new Pieces();
piece1.drawIt(board, true);
// piece2 = new Pieces();
// piece2.drawIt(board, false);
ANIMATION_DELAY = 500;
public void init()
JPanel panel = new beginGame();
add(panel);
public class beginGame extends JPanel
public beginGame()
setPreferredSize(new Dimension(400,800));
setBackground(Color.white);
public void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
temp_storage_board = board;
for (int i = 0 ; i < yBoard; i++)
for (int j = 0 ; j < xBoard; j++)
if(temp_storage_board[i][j] == 1) drawCross(g2, i, j);
else if(temp_storage_board[i][j] == 2) drawLeftL(g2, i, j);
else if(temp_storage_board[i][j] == 3) drawRightL(g2, i, j);
else if(temp_storage_board[i][j] == 4) drawLeftS(g2, i, j);
else if(temp_storage_board[i][j] == 5) drawRightS(g2, i, j);
else if(temp_storage_board[i][j] == 6) drawSquare(g2, i, j);
else if(temp_storage_board[i][j] == 7) drawTetris(g2, i, j);
else if(temp_storage_board[i][j] == -1) drawDeadSquare(g2, i, j);
public void drawCross(Graphics2D g2, int x, int y)
// piece1.makeCross(board, true);
g2.setColor(Color.red);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
//else if (board[i][x] == 2)
public void drawLeftL(Graphics2D g2, int x, int y)
// piece1.makeLeftL(board, true);
g2.setColor(Color.red);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
//else if (board[i][x] == 3)
public void drawRightL(Graphics2D g2, int x, int y)
// piece1.makeRightL(board, true);
g2.setColor(Color.cyan);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
//else if (board[i][x] == 4)
public void drawLeftS(Graphics2D g2, int x, int y)
// piece1.makeLeftS(board, true);
g2.setColor(Color.orange);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
//else if (board[i][x] == 5)
public void drawRightS(Graphics2D g2, int x, int y)
// piece1.makeRightS(board, true);
g2.setColor(Color.yellow);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
//else if (board[i][x] == 6)
public void drawSquare(Graphics2D g2, int x, int y)
// piece1.makeSquare(board, true);
g2.setColor(Color.blue);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
//else if (board[i][x] == 7)
public void drawTetris(Graphics2D g2, int x, int y)
// piece1.makeTetris(board, true);
g2.setColor(Color.green);
g2.fillRect(x*width,y*height,width,height);
g2.setColor(Color.black);
g2.drawRect(x*width,y*height,width,height);
// else if (board[i][x] == 0)
public void drawBlankSquare(Graphics2D g2, int x, int y)
// piece1.makeBlankSquare(board, true);
g2.setColor(Color.white);
g2.fillRect(x*width,y*height,width,height);
//else if (board[i][x] == -1)
public void drawDeadSquare(Graphics2D g2, int x, int y)
// piece1.makeDeadSquare(board, true);
g2.setColor(Color.gray);
g2.fillRect(x*width,y*height,width,height);
public void startAnimation()
if (animationTimer == null)
animationTimer = new Timer(ANIMATION_DELAY, new TimerHandler());
animationTimer.start();
else
if (!animationTimer.isRunning())
animationTimer.restart();
public class TimerHandler implements ActionListener
public void actionPerformed(ActionEvent actionEvent)
// System.out.println("aP");
piece1.moveDown(board);
// piece1.moveXLeft(board);
piece1.drawIt(board, true);
repaint();
if (piece1.startPlaceY> 10)
piece1.killLiving(board);
//y += size;
//if (y > height) y = 10;
public class KeyHandler implements KeyListener
public void keyPressed(KeyEvent event)
switch (event.getKeyCode())
case KeyEvent.VK_LEFT:
piece1.moveXLeft(board);
//x -= size;
break;
case KeyEvent.VK_RIGHT:
piece1.moveXRight(board);
//x += size;
break;
repaint();
public void keyReleased(KeyEvent event) {}
public void keyTyped(KeyEvent event) {}
Basically, what this does is creates an applet, picks a random piece, and makes the piece fall down until it reaches the end (at which point it can't fall down any further)
As I mentioned before, the method: public class TimerHandler implements ActionListener
public void actionPerformed(ActionEvent actionEvent)
// System.out.println("aP");
piece1.moveDown(board);works, because the thing DOES fall down.
However, when I try to replicate that with the keyListener, using essentially the same process, it doesn't work.
I'll look up what yall said -
JNA: key listener + JFrame
Hello,
I'm trying to write a simple application where I have a keyboard listener in the background and JFrame. Practically, I use the following code to create the listener:
public class KeyHook {
private static volatile boolean quit;
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
System.err.println("in callback, key=" + info.vkCode);
if (info.vkCode == 81) {
quit = true;
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
System.out.println("Keyboard hook installed, type anywhere, 'q' to quit");
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}.start();
// This bit never returns from GetMessage
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
lib.UnhookWindowsHookEx(hhk);
My requirement is to create the listener as the first and after it JFrame. The problem is that I don't know how to create JFrame because of GetMessage. Now, GetMessage blocks the current thread so I can't create JFrame after it. On the other hand, I can't put it in a new Thread because then, the listener doesn't work. I hope you understand the issue :) Any ideas how to solve it?
Thanks in advance!Ok, this is what should be done to solve the problem:
We throw out this fragment:
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}.start();
and next, we enclose code from the main method in:
new Thread(new Runnable() {
}).start();
Then, we are free to type in the main method e.g. :
startListening(); // key listener
JFrame frame = new JFrame();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.setVisible(true);
}); -
What is the best way to implement global key bindings. For example, if a user hits the ESC key from anywhere in a frame, regardless of what component has focus, an action event is fired that calls the frames hide() method. Or when someone hits CTRL-D, another custom action event is fired. Im kind of new to using key bindings and I am just trying to avoid attaching a key binding to a component at random. Any advice, comments, or code would be greatly appreciated. Thanks.
Try the foloowing steps :
1> extract any components inputMap like this
inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) ;
2> Put the the keyStroke in it along with the action
inputMap.add(KeyStroke ,Instacne of ActionListener);
hope that helps
Maybe you are looking for
-
Re: we accidently signed up to receive apps from our new printer-HP Officejet Pro 8600 Plus
Sir Pleasr stop appps services thank you
-
How do I identify an executable's path at run time?
I am developing an application for deployment as an executable via an installation package. This application will need an accompanying initialization file which will store user configurable defaults (such as the root path to his data and other sundri
-
Hey folks-- I've created a site with some Flash buttons for navigation. I created them within Dreamweaver MX 2004. I'm using Mac OSX. Here's the problem: when I upload the files to the server, the flash button links work in Safari. They do not work i
-
Limiting ADF table number of rows is not working
Dear All, I know this question might seems to be a little bit trivial but I have been going in circles for a long time now and can't figure out where I'm going wrong, I'm using Jdeveloper 11g TP4 and developing an ADF RC application, I have a table t
-
Viewing firewire external device and VGA monitor with mirroring off
My mac laptop is connected to an external monitor via the VGA port and I keep mirroring off to maximize display space. When using FCP I want to run firewire out to a professional DVcam deck for both capture, and to view the timeline on an external mo