捕获java中面板中的击键

时间:2010-05-13 07:08:19

标签: java swing keyboard-events

我希望在焦点放在java中的面板上时捕获击键。我该怎么办?

我使用Netbeans作为IDE。我尝试添加keyTyped事件,但它不起作用。

这是我的代码

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;
}

5 个答案:

答案 0 :(得分:4)

实际上,你想要的是一个KeyboardManager来安装KeyEventPostProcessor,甚至是各种组件的备用调度。我在NB应用程序中遇到了和你一样的问题。

以下是我使用的文章:(developer.com

我这样做是为了从面板中的任何控件捕获输入键事件(自动启动“OK”按钮行为):

    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventPostProcessor(new EnterKeyListener());

听众:

    class EnterKeyListener implements KeyEventPostProcessor {

    @Override
    public boolean postProcessKeyEvent(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            //Activate the refresh button:
            fireSearch();
            return true;    //halt further processing
        }
        return false;
    }
}

答案 1 :(得分:3)

不要忘记调用setFocusable(true),如How to Write a Key Listener中所述。

答案 2 :(得分:2)

您需要向面板添加新的FocusListener和新的KeyListener。如果您只想在面板处于焦点时捕获按键,请获取FocusListener的操作以添加KeyListener并将其删除。

答案 3 :(得分:2)

KeyListener添加到您的面板:

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

    public void keyTyped(KeyEvent e) { … }

    public void keyReleased(KeyEvent e) { … }

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

使用相应的方法处理事件。

正如其他人精确提到的那样,您必须设置panel.setFocusable(true);,当然,您应该将此组件添加到您的框架(或其他父组件)。

答案 4 :(得分:0)

根据您想要达到的目标,您也可以在此处找到帮助:http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html