1

我有一个显示缓冲图像的功能。我希望在加载图像的 JLabel 中实现鼠标侦听器和按键侦听器。由于 JLabel 无法获得焦点,我尝试使用 KeyBinding。但我注意到 KeyBinding 用于个人密钥。我想要的是每个按下的键的键码,而不管按下的是什么键。有没有办法在这种情况下获得 KeyCode?我还注意到 KeyListener 和 MouseListener 在构造函数中有效,但在其他方法中无效。是真的吗?

 public void imageloader(BufferedImage image) throws InterruptedException {
        // frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension dimension = new Dimension(image.getWidth(), image.getHeight());
        setSize(200, 100);
        setVisible(true);
        label.removeAll(); //label is Jlabel
        label.setIcon(new ImageIcon(image));
        frame.setSize(dimension);
        label.revalidate();
        JScrollPane pane = new JScrollPane(label,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        frame.getContentPane().add(pane);
        frame.setSize(dimension);
       // frame.setVisible(true);
    }

更新:

我改变了方法,仍然无法获得键盘焦点,尽管触发了鼠标事件。

public void imageloader(BufferedImage image) throws InterruptedException {
 final String eol = System.getProperty("line.separator");
        final JTextArea ta = new JTextArea(15, 60);
        ta.setEditable(false);
        Dimension dimension = new Dimension(Bimage.getWidth(), Bimage.getHeight());
        gui.add(new JScrollPane(ta), BorderLayout.CENTER);

        gui.add(l, BorderLayout.NORTH);
        gui.setSize(dimension);
        l.setFocusable(true);
        //l.setOpaque(true);
        l.removeAll();
        l.setIcon(new ImageIcon(Bimage));
        l.revalidate();
        l.addFocusListener(new FocusListener() {
            Color focused = Color.CYAN;
            Color unfocused = Color.ORANGE;

            public void focusLost(FocusEvent fe) {
                System.out.println("Unfocused");
            }

            public void focusGained(FocusEvent fe) {
                System.out.println("Focused");

            }
        });

        l.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseEntered(MouseEvent me) {
                System.out.println("Mouse Entered");
            }

            @Override
            public void mouseExited(MouseEvent me) {
                System.out.println("Mouse Exited");

            }

            public void mouseClicked(MouseEvent e) {
                System.out.println("Mouse Clicked");
            }
        });
        l.addKeyListener(new KeyAdapter() {

            @Override
            public void keyTyped(KeyEvent ke) {
                System.out.println("Key Typed");
            }

            public void keyPressed(KeyEvent e) {
                System.out.println("Key Pressed");
            }
        });

        frame.getContentPane().add(gui);
        frame.setSize(dimension);
    }
4

2 回答 2

2
I don't know from where you knew JLabel can get Focus. 
Documentation here clearly explains it cannot get Keyboard Focus.

让我们回到KeyBindings

myLabel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
    KeyStroke.getKeyStroke((KeyEvent.DEL), 0, false), "DELETE");

   myLabel.getActionMap().put("DELETE", new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
          //       any/some Action
      }
   });
于 2011-11-02T07:49:23.050 回答
1

JLabel 无法获得焦点

当然可以。

import java.awt.Color;
import java.awt.event.*;
import javax.swing.*;

class LabelFocus {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                final JLabel l = new JLabel("Focus now!");
                l.setFocusable(true);
                l.setOpaque(true);
                l.addFocusListener(new FocusListener(){
                    Color focused = Color.CYAN;
                    Color unfocused = Color.ORANGE;
                    public void focusLost(FocusEvent fe) {
                        l.setBackground(unfocused);
                    }
                    public void focusGained(FocusEvent fe) {
                        l.setBackground(focused);
                    }
                });
                JOptionPane.showMessageDialog(null, l);
            }
        });
    }
}

更新

现在我已经更仔细地阅读了这个问题,这是一个在标签中检测焦点、鼠标键类型事件的示例。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class LabelFocus {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JPanel gui = new JPanel(new BorderLayout(3,3));
                final String eol = System.getProperty("line.separator");
                final JTextArea ta = new JTextArea(15,60);
                ta.setEditable(false);
                gui.add(new JScrollPane(ta), BorderLayout.CENTER);
                final JLabel l = new JLabel("Focus now!");
                gui.add(l, BorderLayout.NORTH);
                l.setFocusable(true);
                l.setOpaque(true);

                l.addFocusListener(new FocusListener(){
                    Color focused = Color.CYAN;
                    Color unfocused = Color.ORANGE;
                    public void focusLost(FocusEvent fe) {
                        l.setBackground(unfocused);
                        ta.append(fe.toString());
                        ta.append(eol);
                    }
                    public void focusGained(FocusEvent fe) {
                        l.setBackground(focused);
                        ta.append(fe.toString());
                        ta.append(eol);
                    }
                });

                l.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseEntered(MouseEvent me) {
                            ta.append(me.toString());
                            ta.append(eol);
                        }
                        @Override
                        public void mouseExited(MouseEvent me) {
                            ta.append(me.toString());
                            ta.append(eol);
                        }
                    });
                l.addKeyListener(new KeyAdapter() {
                        @Override
                        public void keyTyped(KeyEvent ke) {
                            ta.append(ke.toString());
                            ta.append(eol);
                        }
                    });

                JOptionPane.showMessageDialog(null, gui);
            }
        });
    }
}

示例输出

java.awt.FocusEvent[FOCUS_GAINED,permanent,opposite=javax.swing.JButton[OptionPane.button,335,6,39x26,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@1813fac,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=java.awt.Insets[top=2,left=8,bottom=2,right=8],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=OK,defaultCapable=true],cause=TRAVERSAL_FORWARD] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='s',keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='d',keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='f',keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='s',keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='d',keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.KeyEvent[KEY_TYPED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar='f',keyLocation=KEY_LOCATION_UNKNOWN,rawCode=0,primaryLevelUnicode=0,scancode=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.FocusEvent[FOCUS_LOST,permanent,opposite=javax.swing.JTextArea[,0,0,4970x240,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.basic.BasicBorders$MarginBorder@1855af5,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=false,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],colums=60,columWidth=11,rows=15,rowHeight=16,word=false,wrap=false],cause=TRAVERSAL_FORWARD] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.MouseEvent[MOUSE_ENTERED,(215,14),absolute(867,418),button=0,clickCount=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
java.awt.event.MouseEvent[MOUSE_EXITED,(220,19),absolute(872,423),button=0,clickCount=0] on javax.swing.JLabel[,0,0,663x16,alignmentX=0.0,alignmentY=0.0,border=,flags=25165832,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,horizontalAlignment=LEADING,horizontalTextPosition=TRAILING,iconTextGap=4,labelFor=,text=Focus now!,verticalAlignment=CENTER,verticalTextPosition=CENTER]
于 2011-11-02T05:55:22.287 回答