views:

187

answers:

4

I want to capture keystrokes when the focus in on a panel in java. What should i do?

I am using Netbeans as the IDE. I tried adding keyTyped event but it doesnot work.

Here goes my code

import com.lanadmin.Interface.ClientInterface;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.rmi.Naming;
import java.util.logging.Level;


public class RemoteViewer extends javax.swing.JInternalFrame {


    public RemoteViewer() {
        initComponents();
        rdpanel.setFocusable(true);
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        rdpanel = new javax.swing.JPanel();
        setFocusable(true);

        rdpanel.setToolTipText("Remote Desktop");
        rdpanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                rdpanelMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                rdpanelMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                rdpanelMouseReleased(evt);
            }
        });
        rdpanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                rdpanelMouseMoved(evt);
            }
        });
        rdpanel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                rdpanelFocusGained(evt);
            }
        });
        rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rdpanelKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rdpanelKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rdpanelKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout rdpanelLayout = new javax.swing.GroupLayout(rdpanel);
        rdpanel.setLayout(rdpanelLayout);
        rdpanelLayout.setHorizontalGroup(
            rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 679, Short.MAX_VALUE)
        );
        rdpanelLayout.setVerticalGroup(
            rdpanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 626, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rdpanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        
    private void rdpanelMouseMoved(java.awt.event.MouseEvent evt) {                                   
        double xScale = Toolkit.getDefaultToolkit().getScreenSize().getWidth() / rdpanel.getWidth();
        double yScale = Toolkit.getDefaultToolkit().getScreenSize().getHeight() / rdpanel.getHeight();
        try {
            String current = Login.handler.currentClientAddress.getHostAddress();
            ClientInterface client = (ClientInterface) Naming.lookup("rmi://" + current + "/lan");
            client.mousemove((int) (evt.getX() * xScale), (int) (evt.getY() * yScale));
        } catch (Exception ex) {
            Log2File.logger.log(Level.SEVERE, null, ex);
            Log2File.fileHandler.flush();
        }
    }                                  
    private void rdpanelKeyPressed(java.awt.event.KeyEvent evt) {                                   
        System.out.println("keypressed");
    }                                  
    private void rdpanelKeyTyped(java.awt.event.KeyEvent evt) {                                 
        System.out.println("aaa");
    }                                
    private void rdpanelKeyReleased(java.awt.event.KeyEvent evt) {                                    
        System.out.println("keyreleased");
    }                                   
   private void rdpanelFocusGained(java.awt.event.FocusEvent evt) {                                    
        rdpanel.addKeyListener(new java.awt.event.KeyAdapter() {
           @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
                rdpanelKeyPressed(evt);
            }
            @Override
            public void keyReleased(java.awt.event.KeyEvent evt) {
                rdpanelKeyReleased(evt);
            }
            @Override
            public void keyTyped(java.awt.event.KeyEvent evt) {
                rdpanelKeyTyped(evt);
            }
        });
    }                                   
    public javax.swing.JPanel rdpanel;
}
+2  A: 

You need to add a new FocusListener and a new KeyListener to the panel. If you only want the keystrokes captured when the panel is in focus, get the FocusListener's action to add the KeyListener and remove it.

Finbarr
+1  A: 

Add KeyListener to your panel:

JPanel panel = new JPanel();
panel.addKeyListener(new KeyListener() {

    public void keyTyped(KeyEvent e) { … }

    public void keyReleased(KeyEvent e) { … }

    public void keyPressed(KeyEvent e) { … }
});

Handle event with the corresponding method.

As others precisely mentioned, you have to set panel.setFocusable(true); and, naturally, you ought to add this component to your frame (or other parent component).

Bar
i hav added the key listener..it doesn't work.
rgksugan
+1  A: 

Depending on what you want to achieve, you could maybe also find help here: http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html

fish
tried it even then it doesnot works
rgksugan
Did you move the focus to that component, by clicking with your mouse? Still nothing?
fish
yeah i clicked the panel with my mouse and still nothing..
rgksugan
Ok, removed that useless suggestion, but I'd suggest you take a look at the link and specifically ActionMap and InputMap there. Those might be what you are after.
fish
+2  A: 

Don't forget to invoke setFocusable(true), as discussed in How to Write a Key Listener.

trashgod