Window keylistener

Hi,
i wanna add a keylistener to the keyboard , i mean if i run my program it will listen to all the typed keys, ?
so can i put a keylistener on a window ? or is there a keylistener which listen only to the keyboard , even if my window is not selected ?
i hope u got me :)
thank you for your help

Hi,
I hope we can do that with JNI and KeyboardHooking.
this code worked fine when the aplication has the focus , but it didn't work when the applicaion is out of focus, i dont have any clue about that.
#include <stdio.h>
#include <windows.h>
#include "jni.h"
#include "JNIFrame.h"
#include <process.h>
//HINSTANCE hInst;
//HHOOK g_hook = NULL;
jclass cls1;
//jobject obj1;
JNIEnv *env1;
//JavaVM *pJavaVM;
jmethodID mid;
#pragma data_seg("Shared")
HHOOK g_hook = NULL;
HINSTANCE hInst = NULL;
JavaVM *pJavaVM = NULL;
jobject obj1 = NULL;
#pragma data_seg()
#pragma comment(linker,"/SECTION:Shared,RWS")
LRESULT CALLBACK KeyboardProc(int code, WPARAM wParam, LPARAM lParam);
int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpvReserved);
int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpvReserved)
hInst=hInstance;
return TRUE;
JNIEXPORT void JNICALL Java_JNIFrame_initialize(JNIEnv *env, jclass cls,jobject obj)
//jclass cls = (*env)->GetObjectClass(env, obj);
cls1=cls;
obj1=obj;
env1=env;
//g_hook = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyboardProc, hInst,(DWORD)NULL);
env->GetJavaVM(&pJavaVM);
mid = env->GetMethodID(cls, "callback", "()V");
g_hook = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyboardProc, hInst,(DWORD)NULL);
LRESULT CALLBACK KeyboardProc(
int nCode, // hook code
WPARAM wParam, // current-process flag
LPARAM lParam // address of structure with message data
JNIEnv *__env;
printf("sravan5");
#if defined(JDK1_2) || defined(JDK1_3)
pJavaVM->AttachCurrentThread((void**)&__env, (void*) 0);
#else
pJavaVM->AttachCurrentThread(&__env, (void*)0);
#endif
if(nCode>=0)
// jmethodID mid = __env->GetMethodID(cls1, "callback", "()V");
if (mid == 0) {
printf("sravan4");
return 0;
printf("sravan5");
__env->CallVoidMethod(obj1,mid);
return CallNextHookEx(g_hook, nCode, wParam, lParam);
JNIEXPORT void JNICALL Java_JNIFrame_unHook
(JNIEnv *, jclass, jobject)
UnhookWindowsHookEx(g_hook);

Similar Messages

  • Inactive Window - keyListener

    i have a problem. I wrote a program, that reacts on a keyevent. That works, but only if the window of my program is active. And theres the problem, because it should even react on the keyevent if another window is active.
    It this possible in Java? If not, what are the alternatives?
    judy

    Hi judy333!
    Unfortunatelly I never exploited this issue in Java, but think about calling C-language programs just to listen environment events and to notify program, ie; removing from dormant state (inactive). As you can see, it is a hack on OS, be careful! In past I was successful using Object Pascal and MASM but I do not consider it a good solution!
    Good luck and success!
    (also try forum about native methods)

  • Problem using KeyListener in a JFrame

    Let's see if anyone can help me:
    I'm programming a Maze game, so I use a JFrame called Window, who extends JFrame and implements ActionListener, KeyListener. Thw thing is that the clase Maze is a JPanel, so I add it to my Frame and add the KeyListener to both, the Maze and the Window, but still nothing seems to happen.
    I've tried to remove the KeyListener from both separately, but still doesn't work...
    Any suggestions???

    This is the code for my Window.java file. May be someone can see the error...
    package maze;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Window extends JFrame implements ActionListener, KeyListener {
      private Maze maze;
      private JButton crear = new JButton("New");
      public Window(int size, String s) {
        super("3D Maze");
        boolean b = true;
        if (s.equalsIgnoreCase("-n"))
          b = false;
        else if (s.equalsIgnoreCase("-v"))
          b = true;
        Container c = getContentPane();
        c.setLayout(new BorderLayout());
        maze = new Maze(size,size,b);
        crear.addActionListener(this);
        addKeyListener(this);
        maze.addKeyListener(this);
        c.add(crear,BorderLayout.NORTH);
        c.add(maze,BorderLayout.CENTER);
        setSize(600,650);
        show();
      public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == e.VK_UP || e.getKeyCode() == e.VK_W)
          maze.walk();
        else if (e.getKeyCode() == e.VK_DOWN || e.getKeyCode() == e.VK_S)
          maze.back();
        else if (e.getKeyCode() == e.VK_LEFT || e.getKeyCode() == e.VK_A)
          maze.turnLeft();
        else if (e.getKeyCode() == e.VK_RIGHT || e.getKeyCode() == e.VK_D)
          maze.turnRight();
        else if (e.getKeyCode() == e.VK_V)
          maze.alternaMostrarCreacion();
        else if (e.getKeyCode() == e.VK_M)
          maze.switchMap();
      public void keyTyped(KeyEvent e) {}
      public void keyReleased(KeyEvent e) {
      public void actionPerformed(ActionEvent e) {
        maze.constructMaze();
      public static void main(String[] args) {
        int i = 30;
        String s = "-v";
        if (args.length != 0) {
          try {
            i = Integer.parseInt(args[0]);
            if (!(i >= 15 && i <= 50))
              i = 30;
            s = args[1];
          catch(Exception e) {}
        Window w = new Window(i,s);
        w.addWindowListener(
          new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              ImageIcon im = new ImageIcon("./Logo.gif");
              String s = "";
              s += "3D MAZE\n\n";
              s += "Creator: Allan Marin\n";
              s += "http://metallan.topcities.com\n\n";
              s += ""+((char)(169))+" 2002";
              JOptionPane.showMessageDialog(null,s,"About...",JOptionPane.PLAIN_MESSAGE,im);
              System.exit(0);
    }

  • ActionPerformed method not working when applet is loaded in browser window.

    Hey there guys. I need urgent help from anybody who has experience in deploying websites whose code is in java.
    I am having two problems as mentioned below...
    first, I have made a simple login screen using java swing and JApplet. there is a single button to login. the action performed for this button accesses a private method to check the username and password which are there in atext file. the applet is working perfectly in appletviewer but when i load the applet in a Internet Explorer window using HTML's Applet tag, the button is giving no response at all even when i enter the correct username and password.
    I guess it is either not calling the private function that is checking the username and password from the tes=xt file or it can not access the file. Please help as soon as possible as this is related to my college project.
    I am attaching the code herewith. Suggestions to improve the coding are also welcome.
    the second problem is that while writing my second program for generating a form which registers a user the html is not at all loading the applet into the browser and also if im trying to access a file to write all the details into the console is showing numerous amount of error after i press the button which i can't not understand. the only thing i can understand is that it is related to file access permissions. If anybody could put some light on the working of worker threads and thread safe activities of SwingUtilities.invokeandWait method it would be really appreciable.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    <applet code = "UserLogin" width = 300 height = 150>
    </applet>
    public class UserLogin extends JApplet implements ActionListener, KeyListener {
         private JLabel lTitle;
         private JLabel lUsername, lPassword;
         private JTextField tUsername;
         private JPasswordField tPassword;
         private JButton bLogin;
         private JLabel lLinkRegister, lLinkForgot;
         private JLabel lEmpty = new JLabel(" ", JLabel.CENTER);
         private JPanel panel1, panel2;
         public void init() {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             LoginGUI();
              catch(Exception e) {
                   e.printStackTrace();
         public void start() {
              setVisible(true);
         public void stop() {
              setVisible(false);
         private void LoginGUI() {
              super.setSize(300, 150);
              super.setBackground(Color.white);
              lTitle = new JLabel("<HTML><BODY><FONT FACE = \"COURIER NEW\" SIZE = 6 COLOR = BLUE>Login</FONT></BODY></HTML>", JLabel.CENTER);
              lUsername = new JLabel("Username : ", JLabel.CENTER);
              lPassword = new JLabel("Password : ", JLabel.CENTER);
              tUsername = new JTextField(15);
              tPassword = new JPasswordField(15);
              bLogin = new JButton("LOGIN");
    //          bLogin.setEnabled(false);
              bLogin.addActionListener(this);
              bLogin.addKeyListener(this);
              panel2 = new JPanel();
              GridBagLayout gbag = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              panel2.setLayout(gbag);
              panel2.addKeyListener(this);
              gbc.anchor = GridBagConstraints.CENTER;
              panel2.setMinimumSize(new Dimension(300, 200));
              panel2.setMaximumSize(panel2.getMinimumSize());
              panel2.setPreferredSize(panel2.getMinimumSize());
              gbc.gridx = 1;
              gbc.gridy = 1;
              gbag.setConstraints(lUsername,gbc);
              panel2.add(lUsername);
              gbc.gridx = 2;
              gbc.gridy = 1;
              gbag.setConstraints(tUsername,gbc);
              panel2.add(tUsername);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbag.setConstraints(lPassword,gbc);
              panel2.add(lPassword);
              gbc.gridx = 2;
              gbc.gridy = 2;
              gbag.setConstraints(tPassword,gbc);
              panel2.add(tPassword);
              gbc.gridx = 2;
              gbc.gridy = 3;
              gbag.setConstraints(lEmpty,gbc);
              panel2.add(lEmpty);
              gbc.gridx = 2;
              gbc.gridy = 4;
              gbag.setConstraints(bLogin,gbc);
              panel2.add(bLogin);
              panel1 = new JPanel(new BorderLayout());
              panel1.add(lTitle, BorderLayout.NORTH);
              panel1.add(panel2, BorderLayout.CENTER);
              add(panel1);
              setVisible(true);
         public void keyReleased(KeyEvent ke) {}
         public void keyTyped(KeyEvent ke) {}
         public void keyPressed(KeyEvent ke) {
              if(ke.getKeyCode() == KeyEvent.VK_ENTER){
                   String username = tUsername.getText();
                   String password = new String(tPassword.getPassword());
                   if(username.length() == 0 || password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(),"You must enter a username and password to login", "Error", JOptionPane.ERROR_MESSAGE);
                   else {
                        boolean flag = checkUsernamePassword(username, password);
                        if(flag)
                             JOptionPane.showMessageDialog(new JFrame(),"Username and Password Accepted", "Access Granted", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(new JFrame(),"Username or password Incorrect", "Access Denied", JOptionPane.INFORMATION_MESSAGE);
         public void actionPerformed(ActionEvent ae) {
              String gotCommand = ae.getActionCommand();
              if(gotCommand.equals("LOGIN")) {
                   String username = tUsername.getText();
                   String password = new String(tPassword.getPassword());
                   if(username.length() == 0 || password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(),"You must enter a username and password to login", "Error", JOptionPane.ERROR_MESSAGE);
                   else {
                        boolean flag = checkUsernamePassword(username, password);
                        if(flag)
                             JOptionPane.showMessageDialog(new JFrame(),"Username and Password Accepted", "Access Granted", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(new JFrame(),"Username or password Incorrect", "Access Denied", JOptionPane.INFORMATION_MESSAGE);
         private boolean checkUsernamePassword(String username, String password) {
              String user = null, pswd = null;
              try {
                   FileInputStream fin = new FileInputStream("@data\\userpass.txt");
                   DataInputStream din = new DataInputStream(fin);
                   BufferedReader brin = new BufferedReader(new InputStreamReader(din));
                   user = (String) brin.readLine();
                   pswd = (String) brin.readLine();
              catch(IOException ioe) {
                   ioe.printStackTrace();
              if(username.equals(user) && password.equals(pswd))
                   return true;
              else
                   return false;
    }PLEASE HELP ME GUYS......

    RockAsh wrote:
    Hey Andrew, first of all sorry for that shout, it was un-intentional as i am new to posting topics on forums and didn't new that this kind of writing is meant as shouting. Cool.
    Secondly thank you for taking interest in my concern.No worries.
    Thirdly, as i mentioned before, I am reading i file for checking of username and password. the file is named as "userpass.txt" and is saved in the directory named "@data" which is kept in the same directory in which my class file resides.OK - server-side. That makes some sense, and makes things easier. The problem with your current code is that the applet will be looking for that directory on the end user's local file system. Of course the file does not exist there, so the applet will fail unless the the end user is using the same machine as the server is coming from.
    To get access to a resource on the server - the place the applet lives - requires an URL. In applets, URLs are relatively easy to form. It might be something along the lines of
    URL urlToPswrd = new URL(getCodeBase(), "@data/userpass.txt");
    InputStream is = urlToPswrd.openStream();
    DataInputStream din = new DataInputStream(is);
    So the problem is that it is reading the file and showing the specific output dialog box when i run it through appletviewer.. Huhh. What version of the SDK are you using? More recent applet viewers should report security exceptions if the File exists.
    ..but the same is not happening when i launch the applet in my browser window using the code as written belowHave you discovered how to open the Java Console in the browser yet? It is important.
    Also the answer to your second question
    Also, the entire approach to storing/restoring the password is potentially wrong. For instance, where is it supposed to be stored, on the server, or on the client?is that, as of now it is just my college project so all the data files and the username and password wiles will be stored on my laptop only i.e. on the client only. no server involved.OK, but understand that an applet ultimately does not make much sense unless deployed through a server. And the entire server/client distinction becomes very important, since that code would be searching for a non-existent file on the computer of the end user.

  • How to add a KeyListener to a JInternalFrame

    1). I have Main Window which is an Application window and has a menu. When I click on a menu option,
    a user interface which is a JInternalFrame type, with JTextFields in it, is loaded.
    2). In the first JTextField(e.g. Employee Number), I have a KeyListener added to the JInternalFrame.
    3). When I enter an Employee number in the JTextField and press the Key F10, I have to fetch the details about the Employee
    (his first name, middle name, last name etc.) from the database and display these details in the corresponding
    JTextFields in the user interface.
    PROBLEM:
    I am able to add a KeyListener to the JInternalFrame but it does not work the way I need it to.
    The moment F10 key is pressed, the JInternalFrame looses focus, and the focus goes to the Main Window and does not execute
    the code for the keyPressed event that is there in the listener.
    How do I overcome this issue??
    The code that I am using is below
    public class TD {
    public void invoke(){
    cFrame = new JInternalFrame("TD Form",
    false, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    // More code here..................
    //Destroy the TD Window.
    cFrame.addInternalFrameListener(new InternalFrameAdapter() {
         public void internalFrameClosing(InternalFrameEvent evt){
                   cancelSteps();
    }); // end of InternalFrameListener.
    cFrame.addKeyListener(new KeyTD(this)); // Adding the KeyListener here to the JInternalFrame
    cFrame.setVisible(true);
    cFrame.setSize(800,450);
    cFrame.setLocation(10,10);
    } // end of the constructor.
    // Inner class that implements the KeyListener
    class KeyTD implements KeyListener {
    private int msg =JOptionPane.INFORMATION_MESSAGE;
    private String title = "KeyPress Event Message";
    Container cornbut;
    TD objTD;
    private int UTNum;
    public KeyTD(TD objTD){
              this.objTD = objTD;
    public void keyPressed(KeyEvent ke){
    int key1 = ke.getKeyCode();
    switch(key1){
    case KeyEvent.VK_F9:
    tD_F9();
    break;
    case KeyEvent.VK_F10:
    UTNum = getNum(); // Reads the content of the JTextField and gets the Integer value
    if (UTNum > 0){
                        tD_F10();
    }else{
    JOptionPane.showMessageDialog(cornbut," Please enter the Number. ",title,msg);
    break;
    }//end of keyPressed method
    public void keyReleased(KeyEvent ke){
    public void keyTyped(KeyEvent ke){
    public void tD_F9(){
    //sets focus to the Text Field where the key listener has been added
    }//end of tD_F9 method
    public void tD_F10(){
    String str = String.valueOf(UTNum);
    Objdbdef.fetchTaskDefiner(str,"", "","" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ,"" );
    if(//there are records in the database then){                       
    // If there are records matching the number from the JTextField the display statements are here.........
    }else{
    JOptionPane.showMessageDialog(cornbut,"There are no records found for the specified criteria.",title,msg);
    }//end of td_F10 method
    }// end of KeyTD class

    As a rule of thumb, I never use KeyListeners, unless you want to listen to many different key strokes.
    Instead, use ActionMap/InputMap. You can attach an action to, say your desktop, that
    is activated when F1 is pressed WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or
    WHEN_IN_FOCUSED_WINDOW

  • A sort of KeyListener without a GUI Component?

    a sort of KeyListener without a GUI Component? ( or any trick that will do)?
    please be patient with my question
    I can't express myself very well but it's very important.
    Please help me I need an example how to implement
    a way to detect some combination of keystrokes in java without
    any GUI ( without AWT or Swing frames ...)
    just the console (DOS or Linux shell window) or with a minimzed
    java frame (awt or swing...) you know, MINIMIZED= not in focus.
    in other words if the user press ctrl + alt +shift ...or some
    other combination... ANYTIME ,and the java program is running in the
    background, is there a way to detect that,
    ... my problem if I use a frame (AWT or SWING) the windows must
    be in focus and NOT MINIMIZED..
    if I use
    someObject.addKeylistener(someComponent);
    then the "someComponent" must be in focus, am I right?
    What I'm coding is a program that if you highlight ANY text in
    ANY OS window, a java window (frame) should pop up and match the
    selected text in a dictionary file and brings me the meaning
    ( or a person's phone number , or
    a book author ...etc.)
    MY CHALLENGE IS WITHOUT PRESSING (Ctrl+C) to copy and paste
    ...etc. and WITHOUT MONITORING THE OS's CLIPBOARD ...I just want to
    have the feature that the user simply highlight a text in ANY
    window anywhere then press Ctrl+shift or some other combination,
    then MY JAVA PROGRAM IS TRIGGERED and it should EMULATE SOME
    KEYSTROKES OF Ctrl+C and then paste the clipboard
    somewhere in my program...with all that AUTOMATION BEING in the background.
    remember that my whole program ALL THE TIME MUST BE MINIMIZED AND
    NOT IN FOCUS
    or just running in the background (using javaw)..
    is there any trick ? pleeeeeeze!!!
    i'm not trying to write a sort of the spying so-called "key-logger"
    purely in java but it's a very similar challenge.
    please reply if you have questions
    I you could please answer me , then guys this would be very
    valuable technique that I need urgently. Thanks!

    DO NOT CROSS POST especially since this has nothing to do with game development at all. I can understand if it was in Java programming and New to Java but even then pick a forum and post it to that one and that one only.

  • Some problems with fullscreen, keylistener and bufferstrategy :-)

    Hi.
    I have a few questions.
    I worked a long time trying to make my game run smoothly but I just couldn't get it perfect. I thought it had something to do with the load of graphics I use, but it wasn't the case. Here is what I did:
    public class Game extends Frame implements Runnable, KeyListener {
        int [] controls = new int[256];
        final static int FrameRate = 60;
        final int MiliFrameLength = 1000/FrameRate;
        private long startTime;
        private int frameCount;
        public Game()
            GraphicsDev gd = new GraphicsDev(); // Class that handles the graphics device
            int ref = gd.getDisplayM().getRefreshRate();
            if(fullscreen==1) {
                setUndecorated(true);
                gd.getGraphicsDev().setFullScreenWindow(this);
                gd.getGraphicsDev().setDisplayMode(new DisplayMode(screenWidthX,screenWidthY,24,ref));
            } else if (fullscreen==0) {
                setSize(screenWidthX,screenWidthY);
            addKeyListener(this);
            show();
            createBufferStrategy(2);
            buffer = getBufferStrategy();
            startTime = System.currentTimeMillis();
            frameCount = 0;
            Thread t = new Thread(this);
            t.start();
            update();
        public void update() {
            while(rungame)  {
                Graphics2D gr2D = (Graphics2D)buffer.getDrawGraphics();
                if(controls[40] == 1) moveup(1);
                if(controls[38] == 1) movedown(1);
                if(controls[37] == 1) moveleft(1);
                if(controls[39] == 1) moveright(1);
                paintGraphics(gr2D);
                gr2D.dispose();
                buffer.show();
                frameCount++;
                while((System.currentTimeMillis()-startTime)/MiliFrameLength <frameCount)
                { Thread.yield(); }
        public void keyPressed(KeyEvent ke) {
             controls[ke.getKeyCode()&0xFF] = 1;
        public void keyReleased(KeyEvent ke) {
             controls[ke.getKeyCode()&0xFF] = 0;
          public void keyTyped(KeyEvent ke){}
    }The original code is of cause much bigger, so this is just to show what happens. It's pretty straight forward.
    My problem is that the game only runs completely smooth when it is in fullscreen and v-synched. This means that I have to have a framerate at 60 (same as the refreshrate). It looks great, but my keyboard input can't keep up with this speed. About every 10 sec the game hangs for a while. If I set the framerate or refreshrate lower it doesn�t run smoothly.
    My questions are:
    1: Is it possible to make the keyboard work with a framerate/refreshrate of 60+
    2: Is it possible to use v-synched in window mode?
    3: If yes � How do I do this? ;-)
    Maybe I'm taking a totally wrong approach to this, but everyone seems to have different solution to making a game to run smooth, and right now I'm very confused (was first yesterday I found out about the v-synch).

    I've seen this code before. You're following a standard rendering template right? I've never used the
    while((System.currentTimeMillis()-startTime)/MiliFrameLength <frameCount)
                { Thread.yield(); } method for syncing framerate but here's another suggestion which
    is what I use and my rendering is as smooth as silk even at a monitor refresh rate (and framerate)
    of 85 fps (however, like you, I only go to 60 fps) long framerate = 60;  //i.e. 60 fps
       public final void run(){
          long start_Time = 0;
          long elapsed_Time = 0;
          final Thread t = Thread.currentThread();
          while(t == thread){
             //start_Time = . . .
             render();
             relocate_Sprites();
             sort_Sprites_for_Z_Buffer();
             //elapsed_Time = . . .
             try{
                if(elapsed_Time < 1000/framerate)
                   Thread.sleep(1000/framerate-elapsed_Time);
                else
                   Thread.sleep(3); // without this line, you may starve the gc
             catch(InterruptedException e){
       }This system works perfectly even with 40 Sprites, one of which is like 1050 x 640 in dimensions
    (background which scrolls a bit). My system is not particularly fast:
    -AMD Athlon 1.2 GHz
    -384 MB RAM
    -nVidia GeForce 2 400 MX at 32 MB (this piece is practically extinct now)

  • KeyListener no longer working in JPanel

    Hi,
    I have implemented a graphics interface with JPanel with mouse action and movement captured. Everything works fine until I added KeyListener implementation.
    No matter what I do, I could not enable the key event.
    The top window is a JFrame which contains several components and one of them is a JPanel. I wanted to capture key event inside that JPanel.
    JFrameC a = new JFrameC();
    JPanelC b = new JPanelC(a);
    And inside JPanelC, I have statement as
    a.addKeyListener(this);
    addKeyListener(this);
    But still no key event.
    If I simply change JPanelC class from JPanel to Panel (only extends statement), key event appears as it supposes to be.
    What's wrong with JPanel? I thought it should behave similar to Panel with more better features.
    What should I do to enable key event in JPanel?
    Please help.

    I tried the following simple program which is similar to my complicated implementation and it worked. I am confused.
    <pre>
    //KeyFrame.java
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.*;
    public class KeyFrame extends JFrame {
    public KeyFrame(String s) {
    super(s);
    KeyEventDemo ked = new KeyEventDemo(this);
    getContentPane().add(ked);
    pack();
    show();
    setSize(500, 500);
    validate();
    public static void main(String [] args) {
    KeyFrame kf = new KeyFrame("");
    // KeyEventDemo.java
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.BorderLayout;
    import java.awt.*;
    public class KeyEventDemo extends JPanel
    //implements KeyListener, ActionListener {
    implements KeyListener {
    public KeyEventDemo(Component c) {
    super();
    c.addKeyListener(this);
    //addKeyListener(this);
    /** Handle the key typed event from the text field. */
    public void keyTyped(KeyEvent e) {
    System.err.println("KEY TYPED: ");
    /** Handle the key pressed event from the text field. */
    public void keyPressed(KeyEvent e) {
    System.err.println("KEY PRESSED: ");
    /** Handle the key released event from the text field. */
    public void keyReleased(KeyEvent e) {
    System.err.println("KEY RELEASED: ");
    </pre>

  • Cannot get KeyListener to work with JAI ScrollImagePanel

    I am trying to display a TIF image and use the page up and page down keys to show page 1 and page 2 of the image. I started with an example for the JAI documentation.
    The problem is that I can't get the key event listener to "see" keystokes.
    I think ScrollImagePanel() is doing its own event listening and I don't know how to get at it.
    Here is the code:
    // http://java.sun.com/products/java-media/jai/forDevelopers/samples/MultiPageRead.java
    A single page of a multi-page TIFF file may loaded most easily by using the page
    parameter with the "TIFF" operator which is documented in the class comments of
    javax.media.jai.operator.TIFFDescriptor. This example shows a
    means of loading a single page of a multi-page TIFF file using the ancillary codec
    classes directly.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.io.IOException;
    import java.awt.image.RenderedImage;
    import java.awt.image.renderable.ParameterBlock;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    public class MultiPageRead4 extends Frame
                implements KeyListener {                              //1
        ScrollingImagePanel panel;
        File file = null;
        ImageDecoder dec = null;
        RenderedImage op = null;
        // side to load, 0=front and 1=back
        static int imageToLoad = 0;
        /** The key code to flip between back and front images */
        private static final int FLIP_IMAGE_KEY1 = KeyEvent.VK_PAGE_UP;
        private static final int FLIP_IMAGE_KEY2 = KeyEvent.VK_PAGE_DOWN;
        /** Short cut key to exit the application */
        private static final int EXIT_KEY = KeyEvent.VK_ESCAPE;
        public MultiPageRead4(String filename) throws IOException {  //2
            super("Multi page TIFF Reader");
            // won't work here either
            // addKeyListener(this);
            addWindowListener(new WindowAdapter() {                  //3
               public void windowClosing(WindowEvent we) {           //4
               System.exit(0);
               }                                                     //4
            });                                                      //3
            if(file == null) {                                       //3
                file = new File(filename);
                SeekableStream s = new FileSeekableStream(file);
                TIFFDecodeParam param = null;
                dec = ImageCodec.createImageDecoder("tiff", s, param);
                System.out.println("Number of images in this TIFF: " +
                                   dec.getNumPages());
                // Which of the multiple images in the TIFF file do we want to load
                // 0 refers to the first, 1 to the second and so on.
                // int imageToLoad = 1;
                }                                                    //3
            // display side of tiff indicated by imageToLoad which is initialized to 0
            // and set by page up / page down
            displaySide();
            }                                                         //2
        // Methods required by the KeyListener interface.
         * Process a key being pressed. Does nothing as we wait for the
         * release before moving.
         * @param evt The event that caused this method to be called
        public void keyPressed(KeyEvent evt)
             System.out.println("Key pressed.");   // debug -- see if it works
            // do nothing
         * Process a key being type (press and release). Does nothing as this is
         * always dodgy about when we get the event. Better to look for the
         * release.
         * @param evt The event that caused this method to be called
        public void keyTyped(KeyEvent evt)
             System.out.println("Key typed.");    // debug -- see if it works
            // do nothing
         * Process a key being pressed. Does nothing as we wait for the
         * release before moving.
         * @param evt The event that caused this method to be called
        public void keyReleased(KeyEvent evt)
        {                                                              //2
            System.out.println("Key released.");  // debug -- see if it works
            switch(evt.getKeyCode())
            {                                                         //3
                case EXIT_KEY:
                    System.exit(0);
                    break;
                case FLIP_IMAGE_KEY1:
                   if(imageToLoad == 1) {                             //4
                      imageToLoad = 0;
                      displaySide();
                      break;
                   }                                                  //4
                case FLIP_IMAGE_KEY2:
                   if(imageToLoad == 0) {                             //4
                      imageToLoad = 1;
                      displaySide();
                      break;
                   }                                                  //4
            }                                                         //3
        }                                                             //2
        public void displaySide() {                                   //2
            try {
                op = new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
                                null,
                                OpImage.OP_IO_BOUND,
                                null);
                }  catch (java.io.IOException ioe) {
                      System.out.println(ioe);
        * Create a standard bilinear interpolation object to be
        * used with the �scale� operator.
           Interpolation interp = Interpolation.getInstance(
                 Interpolation.INTERP_BILINEAR);
        * Stores the required input source and parameters in a
        * ParameterBlock to be sent to the operation registry,
        * and eventually to the �scale� operator.
           ParameterBlock params = new ParameterBlock();
        // params.addSource(image1);
           params.addSource(op);
           params.add(0.70F); // x scale factor
           params.add(0.70F); // y scale factor
           params.add(0.0F); // x translate
           params.add(0.0F); // y translate
           params.add(interp); // interpolation method
        /* Create an operator to scale image1. */
           RenderedOp image2 = JAI.create("scale", params);
        /* Get the width and height of image2 + 3% */
           int width = (int)(image2.getWidth() * 1.03);
           int height = (int)(image2.getHeight() * 1.03);
        /* Attach image2 to a scrolling panel to be displayed. */
           panel = new ScrollingImagePanel(
              image2, width, height);
           panel.addKeyListener(this);
           // Display the original in a 800x800 scrolling window
           // panel = new ScrollingImagePanel(op, 1000, 600);
           add(panel);
           pack();
           show();
                                                                      //2
        public static void main(String [] args) {
            String filename = "034363331.TIF";
            try {
                MultiPageRead4 window = new MultiPageRead4(filename);
                }  catch (java.io.IOException ioe) {
                      System.out.println(ioe);
            System.out.println("finished.");
    // http://java.sun.com/products/java-media/jai/forDevelopers/samples/MultiPageRead.javaI can't get the KeyListener to act (or send the debug messages to System.out.println()).
    If "add( panel );" is removed and the comment before " keyListener(this); " in the constructor the key listening logic works -- of course no image is displayed.
    Thanks for any help.
    Bill Blalock

    Thanks for exanding your explanation. I am not yet skilled enough in Java to follow you completely but I am getting the idea.
    I would appreciate a code snippet using my example so I can better understand. In the mean time I found one way to make it work.
    In the example I eventually found that this change ..
           show();
           panel.requestFocus();enabled the key listener. Bringing the window, even clicking on the panel, didn't give it focus. I understand that the window has to have the focus in order for the key listener to function (different from the mouse listender). I don't understand why the application did not have "focus" even though it was on top and active.
    Oh well, lots to learn.
    Thanks for your suggestion!

  • Command line program: can it implement keyListener??

    Hello,
    before I take the trouble to learn keyListener implementation, I am wondering if my program could even implement it. It is just a small game that just plays in the command window. I would like it to respond to the user pressing up, down, left and right keys. Is this possible with a keyListener or is this only possible in a 'windowed' application?
    And if you cannot register keys this way from the command line, then how would I make my program interactive. Do you know a link to an API description that explains how to set the program up to give a prompt?
    Thank you very much!
    -Mike.

    guess not...

  • JButton keeps JFrame from succesfully implementing KeyListener?!

    Look at this code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame implements KeyListener
         private JButton myButton;
         public Test()
              Container c = getContentPane();
              c.setLayout( new FlowLayout() );
              myButton = new JButton();
              myButton.setEnabled( true );
              c.add( myButton );
              addKeyListener( this );
              setSize( 100, 100 );
              show();
         public void keyPressed( KeyEvent e )
                System.out.println( "keyPressed" );
         public void keyReleased( KeyEvent e )
              System.out.println( "keyReleased" );
         public void keyTyped( KeyEvent e )
              System.out.println( "keyTyped" );
         public static void main( String args[] )
              Test window = new Test();
    }When you execute this program, the JFrame does not resolve keystrokes. It should though, because it implements KeyListener and overrides all required methods. But here is the strange thing: Try changing
    myButton.setEnabled( true );to
    myButton.setEnabled( false );Now the JFrame is able to respond to keystrokes by executing the proper methods! But what use is a button if it is not enabled. I need my buttons in the JFrame, but I also need the JFrame to respond to the keystrokes.
    Anyone know about this problem and how to solve it??
    Thank you!

    ?? Say you want to make a small game. A square is drawn onto the frame. The user presses the up button on the keybord and the square 'moves' up (it is repainted at a different coordinate). But the user also needs to be able to (re)start the game and exit through the use of JButtons. That is the purpose and the problem is stated in my first post...
    Anyone else has an idea?
    thx

  • Using KeyListener

    I'm looking for something similar to some code I wrote in C++ not too long ago. It uses windows.h I believe, and the exact code segments needed are:
    #define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)and then
    if(KEY_DOWN(VK_UP))Basically, what I'm looking for is something that will return a boolean value for a specific key or the value of the key currently being pressed. I think what I want is keylistener, but I can't manage to get any of the examples to work, and a lot of them are quite complicated.
    I'm using Java 5.0 if it matters.

    I'm looking for something similar to some code I
    wrote in C++ not too long ago. It uses windows.h I
    believe, and the exact code segments needed are:
    #define KEY_DOWN(vk_code)
    ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 :
    0)and then
    if(KEY_DOWN(VK_UP))Basically, what I'm looking for is something that
    will return a boolean value for a specific key or the
    value of the key currently being pressed. I think
    what I want is keylistener, but I can't manage to get
    any of the examples to work, and a lot of them are
    quite complicated.
    I'm using Java 5.0 if it matters.I do not code in C++, and so the code you posted I could only guess at. However, that said, I imaging you want KeyEvent.getKeyCode(), and that you want it on keyPressed events. What you wanna do is check out the API docs for the vers you are using and go up and down the list of methods available.
    Posting the code you have tried is - I totally agree - is the best way for any of us to point out what's right from what's wrong ... if you keep the snippet concise and well arranged.
    !!Bill (today)

  • KeyListener in Fullscreen App Help

    I'm working on a fullscreen application in which i need to do some key binding. My class is implementing both the MouseListener interface and the KeyListener interface, I have defined all the methods contained in that interface, and I have added a KeyListener and a MouseListener to my Window. When I click the mouse, my application does everything I defined in the methods of the MouseListener. However, when I hit keys nothing happens. Does anyone know if there is anything extra that I need to do when using a KeyListener with a Window?

    Hi!
    I just wrote exactly what you did two weeks ago. It seems to me as if you forgot to make your object (Frame, JFrame, JLabel,...) focusable. You usually do that by calling myFrame.setFocusable(true); You can find some addidtional help in http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html where you also find a link to a pretty nice piece of code right below point 13 of "Try This[b]".
    Good luck,
    G :-)

  • Why doesnt my keylistener work!?!

    class ers {
    public static void main (String [] args){
    int width = 500;
    int height = 500;
    int keyR=0;
    Slate slate= new Slate (width,height);
    Graphics g = slate.getSlateGraphics();
    g.setColor (Color.white);
    draw (g,0,0,width,height);
    slate.repaint();
    Key1 key = new Key1();
    keyR=Key1.j;
    for (int i =100; i<500; i+=10){
    System.out.println("loop entered");
    if (keyR==10){
    System.out.println("j was called");
    anim(slate,i);
    public static void draw (Graphics g, int x, int y, int width, int height){
    if (height<3) return;
    public static void anim (Slate slate,int i){
    Graphics g= slate.image.getGraphics();
    g.setColor (Color.white);
    g.fillRect(200,i,75,100);
    g.setColor (Color.black);
    g.drawLine (200,i,275,i);
    slate.repaint();
    class Slate extends Frame {
    Image image;
    public Slate (int width, int height){
    setBounds (100, 100, width, height);
    setBackground (Color.green);
    setVisible (true);
    image= createImage(width, height);
    public Graphics getSlateGraphics (){
    return image.getGraphics();
    public void update (Graphics g){
    paint (g);
    public void paint (Graphics g){
    if (image==null)return;
    g.drawImage (image,0,0,null);
    (This is another file)
    import java.*;
    import java.awt.*;
    import java.util.Random;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import java.awt.event.*;
    import javax.swing.*;
    public class Key1 extends JFrame implements KeyListener{
    JTextField KeyCodeT = new JTextField("Key Code:");//A Text Field that will display the key code.
    public Key1(){
    KeyCodeT.addKeyListener(this);//Listens for key inputs in the text field
    KeyCodeT.setEditable(false);//disallow user input into the Text field.
    add(KeyCodeT);//add the text field to the screen
    setSize(300,300);//set the screen ssize
    setVisible(true);//show the window on screen.
    //Called when the key is pressed down.
    public void keyPressed(KeyEvent e){
    System.out.println("Key Pressed!!!");
    j=e.getKeyCode();
    if(e.getKeyCode()==27) {//check if the Keycode is 27 which is esc
    JOptionPane.showMessageDialog(null,"Good Bye");//display a good bye messege
    System.exit(0);//exit
    //Called when the key is released
    public void keyReleased(KeyEvent e){
    System.out.println("Key Released!!!");
    KeyCodeT.setText("Key Code:" + e.getKeyCode());//displays the key code in the text box
    //Called when a key is typed
    public void keyTyped(KeyEvent e){
    public static int j;

    What exactly doesn't work for you? The KeyListener appears to work great on my machine. I suspect you mean that the loop doesn't work. That's because the loop runs very quickly, then exits. I would recommend having the Slate.anim(...) call directly in your KeyListener instead of in a loop.

  • KeyListener on combobox calander not working?

    Am trying to add keylistener on this combobox calander, but somehow its not working right. The calendar is added to a JTable and the keyListener on it works, when i gets focus, but when the popup is visible it looses the keylistener? Can someone help me with this?
    import com.sun.java.swing.plaf.motif.*;
    import com.sun.java.swing.plaf.windows.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.metal.*;
    import javax.swing.table.*;
    public class DateComboBox extends JComboBox
        public DateComboBox()
        public DateComboBox(int raekke,DefaultTableModel model,JTable tabel)
            this.raekke=raekke;
            this.model=model;
            this.tabel=tabel;
        public void setDateFormat(SimpleDateFormat dateFormat)
            this.dateFormat = dateFormat;
        public void setSelectedItem(Object item)
            // Could put extra logic here or in renderer when item is instanceof Date, Calendar, or String
            // Dont keep a list ... just the currently selected item
            removeAllItems(); // hides the popup if visible
            addItem(item);
            super.setSelectedItem(item);
        public void setText(String texte)
            setSelectedItem(texte);
        public String getText()
            return (String)this.getSelectedItem();
        public void setRaekke(int raekke)
            this.raekke=raekke;
        public void updateUI()
            ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
            if (cui instanceof MetalComboBoxUI)
                cui = new MetalDateComboBoxUI();
            } else if (cui instanceof MotifComboBoxUI)
                cui = new MotifDateComboBoxUI();
            } else if (cui instanceof WindowsComboBoxUI)
                cui = new WindowsDateComboBoxUI();
            setUI(cui);
        // Inner classes are used purely to keep DateComboBox component in one file
        // UI Inner classes -- one for each supported Look and Feel
        class MetalDateComboBoxUI extends MetalComboBoxUI
            protected ComboPopup createPopup()
                return new DatePopup( comboBox );
        class WindowsDateComboBoxUI extends WindowsComboBoxUI
            protected ComboPopup createPopup()
                return new DatePopup( comboBox );
        class MotifDateComboBoxUI extends MotifComboBoxUI
            protected ComboPopup createPopup()
                return new DatePopup( comboBox );
        // DatePopup inner class
        class DatePopup implements
        ComboPopup,
        MouseMotionListener,
        MouseListener,
        KeyListener,
        PopupMenuListener
            public DatePopup(JComboBox comboBox)
                this.comboBox = comboBox;
                setFocusable(true);
                addKeyListener(this);
                calendar = Calendar.getInstance();
                // check Look and Feel
                background = UIManager.getColor("ComboBox.background");
                foreground = UIManager.getColor("ComboBox.foreground");
                selectedBackground = UIManager.getColor("ComboBox.selectionBackground");
                selectedForeground = UIManager.getColor("ComboBox.selectionForeground");
                initializePopup();
            //========================================
            // begin ComboPopup method implementations
            public void show()
                try
                    // if setSelectedItem() was called with a valid date, adjust the calendar
                    calendar.setTime( dateFormat.parse( comboBox.getSelectedItem().toString() ) );
                } catch (Exception e)
                {e.printStackTrace();}
                updatePopup();
                popup.show(comboBox, 0, comboBox.getHeight());
            public void hide()
                popup.setVisible(false);
            protected JList list = new JList();
            public JList getList()
                return list;
            public MouseListener getMouseListener()
                return this;
            public MouseMotionListener getMouseMotionListener()
                return this;
            public KeyListener getKeyListener()
                return null;
            public boolean isVisible()
                return popup.isVisible();
            public void uninstallingUI()
                popup.removePopupMenuListener(this);
            // end ComboPopup method implementations
            //======================================
            //===================================================================
            // begin Event Listeners
            // MouseListener
            public void mousePressed( MouseEvent e )
            // something else registered for MousePressed
            public void mouseClicked(MouseEvent e)
            public void mouseReleased( MouseEvent e )
                if (!SwingUtilities.isLeftMouseButton(e))
                    return;
                if (!comboBox.isEnabled())
                    return;
                if (comboBox.isEditable())
                    comboBox.getEditor().getEditorComponent().requestFocus();
                else
                    comboBox.requestFocus();
                togglePopup();
            protected boolean mouseInside = false;
            public void mouseEntered(MouseEvent e)
                mouseInside = true;
            public void mouseExited(MouseEvent e)
                mouseInside = false;
            // MouseMotionListener
            public void mouseDragged(MouseEvent e)
            public void mouseMoved(MouseEvent e)
            public void keyPressed(KeyEvent e)
                if(e.getSource()==this)
                    if(e.getKeyCode()==KeyEvent.VK_CONTROL)
                        System.out.println("keytyped1");
            public void keyTyped(KeyEvent e)
            public void keyReleased( KeyEvent e )
                if(e.getKeyCode()==KeyEvent.VK_CONTROL)
                    System.out.println("keytyped2");
                if ( e.getKeyCode() == KeyEvent.VK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER )
                    togglePopup();
             * Variables hideNext and mouseInside are used to
             * hide the popupMenu by clicking the mouse in the JComboBox
            public void popupMenuCanceled(PopupMenuEvent e)
            protected boolean hideNext = false;
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
                hideNext = mouseInside;
            public void popupMenuWillBecomeVisible(PopupMenuEvent e)
            // end Event Listeners
            //=================================================================
            //===================================================================
            // begin Utility methods
            protected void togglePopup()
                if( isVisible() || hideNext)
                    hide();
                else
                    show();
                hideNext = false;
            // end Utility methods
            //=================================================================
            // Note *** did not use JButton because Popup closes when pressed
            protected JLabel createUpdateButton(final int field, final int amount)
                final JLabel label = new JLabel();
                final Border selectedBorder = new EtchedBorder();
                final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
                label.setBorder(unselectedBorder);
                label.setForeground(foreground);
                label.addMouseListener(new MouseAdapter()
                    public void mouseReleased(MouseEvent e)
                        calendar.add(field, amount);
                        updatePopup();
                    public void mouseEntered(MouseEvent e)
                        label.setBorder(selectedBorder);
                    public void mouseExited(MouseEvent e)
                        label.setBorder(unselectedBorder);
                return label;
            protected void initializePopup()
                JPanel header = new JPanel();
                header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
                header.setBackground(background);
                header.setOpaque(true);
                JLabel label;
                label = createUpdateButton(Calendar.YEAR, -1);
                label.setText("<<");
                label.setToolTipText("Sidste �r");
                header.add(Box.createHorizontalStrut(12));
                header.add(label);
                header.add(Box.createHorizontalStrut(12));
                label = createUpdateButton(Calendar.MONTH, -1);
                label.setText("< ");
                label.setToolTipText("Sidste m�ned");
                header.add(label);
                monthLabel = new JLabel("", JLabel.CENTER);
                monthLabel.setForeground(foreground);
                header.add(Box.createHorizontalGlue());
                header.add(monthLabel);
                header.add(Box.createHorizontalGlue());
                label = createUpdateButton(Calendar.MONTH, 1);
                label.setText(" >");
                label.setToolTipText("N�ste m�ned");
                header.add(label);
                label = createUpdateButton(Calendar.YEAR, 1);
                label.setText(">>");
                label.setToolTipText("N�ste �r");
                header.add(Box.createHorizontalStrut(12));
                header.add(label);
                header.add(Box.createHorizontalStrut(12));
                popup = new JPopupMenu();
                popup.setBorder(BorderFactory.createLineBorder(Color.black));
                popup.setLayout(new BorderLayout());
                popup.setBackground(background);
                popup.addPopupMenuListener(this);
                popup.add(BorderLayout.NORTH, header);
                popup.getAccessibleContext().setAccessibleParent(comboBox);
            // update the Popup when either the month or the year of the calendar has been changed
            protected void updatePopup()
                monthLabel.setText( monthFormat.format(calendar.getTime()) );
                if (days != null)
                    popup.remove(days);
                days = new JPanel(new GridLayout(0, 7));
                days.setBackground(background);
                days.setOpaque(true);
                Calendar setupCalendar = (Calendar) calendar.clone();
                setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
                for (int i = 0; i < 7; i++)
                    int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
                    JLabel label = new JLabel();
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setForeground(foreground);
                    if (dayInt == Calendar.SUNDAY)
                        label.setText("s�n");
                    else if (dayInt == Calendar.MONDAY)
                        label.setText("man");
                    else if (dayInt == Calendar.TUESDAY)
                        label.setText("tir");
                    else if (dayInt == Calendar.WEDNESDAY)
                        label.setText("ons");
                    else if (dayInt == Calendar.THURSDAY)
                        label.setText("tor");
                    else if (dayInt == Calendar.FRIDAY)
                        label.setText("fre");
                    else if (dayInt == Calendar.SATURDAY)
                        label.setText("l�r");
                    //                days.add(label);
                    setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
                setupCalendar = (Calendar) calendar.clone();
                setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
                int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
                for (int i = 0; i < (first-2) ; i++)
                    days.add(new JLabel(""));
                for (int i = 1; i <= setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++)
                    final int day = i;
                    final JLabel label = new JLabel(String.valueOf(day));
                    label.setHorizontalAlignment(JLabel.CENTER);
                    label.setForeground(foreground);
                    label.addMouseListener(new MouseAdapter()
                        public void mouseReleased(MouseEvent e)
                            label.setOpaque(false);
                            label.setBackground(background);
                            label.setForeground(foreground);
                            calendar.set(Calendar.DAY_OF_MONTH, day);
                            hide();
                            comboBox.requestFocus();
                            if (tabel.isEditing())
                                tabel.getCellEditor(tabel.getEditingRow(),
                                tabel.getEditingColumn()).stopCellEditing();
                            model.setValueAt(dateFormat.format(calendar.getTime()),raekke,1);
                            tabel.requestFocus();
                        public void mouseEntered(MouseEvent e)
                            label.setOpaque(true);
                            label.setBackground(selectedBackground);
                            label.setForeground(selectedForeground);
                        public void mouseExited(MouseEvent e)
                            label.setOpaque(false);
                            label.setBackground(background);
                            label.setForeground(foreground);
                    days.add(label);
                popup.add(BorderLayout.CENTER, days);
                popup.pack();
            private JComboBox comboBox;
            private Calendar calendar;
            private JPopupMenu popup;
            private JLabel monthLabel;
            private JPanel days = null;
            private SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");
            //        private int antaldage=1;
            private Color selectedBackground;
            private Color selectedForeground;
            private Color background;
            private Color foreground;
        private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        private int raekke=-1;
        private DefaultTableModel model;
        private JTable tabel;
    }

    come on help plz....

Maybe you are looking for

  • How do I get the music from my Ipod to my Itunes account?

    I recieved an older (2007) IPOD classic.  I want to add it to my computer along with the music already on the IPOD.  How do I start an ITUNES account with this used Ipod and NOT erase all the music already on the IPOD?  Years ago I had to use IPOD ag

  • Does "AirPort Disk" work with RAID arrays?

    I currently have a RAID 10 array consisting of four USB hard drives all attached to a USB hub. I use it with three different macs (two leopard, one tiger) and have never had any problems. I know that you can attach multiple USB hard drives to an AirP

  • Oracle column store db

    I've heard that Oracle 12c will have a column store options similar to what companies like Vertica and SAP Hana have. In a very general question, is this available in the current Oracle 12c release? If so, is anyone using this feature and what is you

  • AI CS 4 crashes on quit

    Search this forum for this topic. But all hints are useless. Finally i wipe the disk and installed CS 4 over a fresh installed Mac OS 10.6 and the crashes persist. I can work the whole day without any probs. Bur when i quit AI CS4 it crashes every da

  • ¿Como importar DBF a Oracle?

    Necesito importar archivos DBF en Oracle, ¿hay componentes que pueden hacer esto?