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

アップデート:

メソッドを変更しましたが、MouseEventsがトリガーされても、KeyBoardFocusを取得できません。

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.

KeyBindingに戻りましょう

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 に答える