如题,jlabel可以通过继承鼠标事件来响应鼠标点击事件,但是在继承键盘事件还是无法响应,请问有什么办法让jlabel响应键盘事件?

解决方案 »

  1.   

    可以使用 model去监听,继承AbstractTableModel。
      

  2.   

    什么情况需要Label监听键盘事件和鼠标事件?
      

  3.   

    如果确实需要,你还不如用一个JTextArea来替代JLabel。
      

  4.   

    感覺用jlabel來監聽鍵盤事件  估計也就是 類似按下某個按鍵  然後改變這個jlabel顏色之類的吧 ?應該用AWTEventListener  就可以吧?
      

  5.   

    用Swing的添加组件的监听器,然后创建一个类继承监听器.
      

  6.   

    搞不懂让jlabel监听键盘事件做什么
      

  7.   

    首先得让JLabel能够接收键盘事件,使用setFocusable
    setFocusablepublic void setFocusable(boolean focusable)    Sets the focusable state of this Component to the specified value. This value overrides the Component's default focusability.    Parameters:
            focusable - indicates whether this Component is focusable
        Since:
            1.4
        See Also:
            isFocusable()
      

  8.   

    没有必要用JLable来相应键盘事件吧,难道JLable里放了很多东西?
    用JPanel 然后添加JLable比较好可以用接口来实现
    新建一个类继承JLable implements ItemListener, MouseListener, FocusListener, KeyListener, ActionListener想要什么有什么,哈哈
      

  9.   

    JLabel用于短文本字符串或图像或二者的显示区。标签不对输入事件作出反应。因此,它无法获得键盘焦点。所以无法监听键盘时间
      

  10.   

    你是不是希望键盘动作的时候,jlabel上显示不同的内容啊?
    KeyStroke   up   =   KeyStroke.getKeyStroke(KeyEvent.VK_UP,0);
    InputMap inputmap= panel.getInputMap(JComponent.WHEN_FOCUSED);
    ActionMap actionmap = panel.getActionMap();
    inputmap.put(up,"up");
    actionmap.put("up",new upAction(this));
      class upAction extends AbstractAction{
        public upAction(){
        }
        public void actionPerformed(ActionEvent e) {
         //你的响应
        }
      }
    其中panel一般是你的contentPane,即获得焦点的panel。
      

  11.   


    jlable.addActionListener(new KeyListener(){
         public void actionPerformed(ActionEvent e) { 
        //你的响应 
        } 
    });
      

  12.   

    同意此观点。请参考一下如下代码:
    package layout.test;import java.awt.Color;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;public class OverlayTest { public static void main(String args[]) {
    JFrame f = new JFrame();
    final JLabel lbl = new JLabel("Hello");
    lbl.setBorder(BorderFactory.createLineBorder(Color.red, 10));
    lbl.setFocusable(true);
    lbl.addKeyListener(new KeyAdapter() {
    public void keyPressed(KeyEvent e) {
    //
    lbl.setText(String.valueOf(e.getKeyChar()));
    }
    }); f.getContentPane().add(lbl);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
    }
    }
      

  13.   

    都是从COMPONENT继承的,你也可以再写一个自己的JLABLE的扩展类,把需要的功能都赋于它。
      

  14.   

    setFocusable 之后就可以触发这个事件了
      

  15.   

    label.addMouseListener(new MouseAdapter(){
     //exp:覆盖里面的类即可
    public void mousePressed(MouseEvent e){
      if(e.getClickCount() >= 2){
       System.out.println(">>>>>>>");
    }
    }});