Using Keybinding to get keycode

南楼画角 提交于 2020-01-11 13:57:48

问题


I have a function that display the buffered image. I want mouse listener and key listener to be implemented in JLabel which loads the image. Since JLabel cannot get focus i tried to use KeyBinding. But what i noticed that KeyBinding is used for individuals key. What i want is keycode of each pressed key irrespective of what key is pressed. is there way to get KeyCode in such conditions? Also i noticed that KeyListener and MouseListener works in Constructor but not in other methods. is it true?

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

UPDATE:

I Changed the Method, still cannot get KeyBoard Focus, though MouseEvents are triggered .

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

回答1:


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

let's back to the 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
      }
   });



回答2:


JLabel cannot get focus

Sure it can.

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

Update

Now I've read the question more carefully, here is an example of detecting focus, mouse and key typed events in a label.

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

Example output

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]


来源:https://stackoverflow.com/questions/7976209/using-keybinding-to-get-keycode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!