2014-02-24 51 views
0

我有一些代碼可以在用戶操作後在屏幕上生成JToolTip。我希望用戶能夠通過點擊或按下按鍵來解除提示(ESC,說)。我可以讓鼠標部分工作,但我無法弄清楚如何/在哪裏捕捉關鍵事件。我懷疑這與焦點有關,但我所有的隨機刺傷都沒有結果。這裏是一個簡短的代碼示例,說明了什麼我試圖:關鍵監聽工作部件將KeyListener添加到JToolTip中

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

import javax.swing.*; 

public class HelloSwing extends JFrame { 

    HelloSwing() { 
    JPanel panel = new JPanel(); 
    JButton button = new JButton("Hello!"); 

    button.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
     final JWindow window = new JWindow(); 
     JToolTip tip = new JToolTip(); 
     tip.setTipText("Here's a tip..."); 
     tip.setVisible(true); 
     window.getContentPane().add(tip); 
     window.pack(); 
     window.setLocation(50, 50); 
     window.setAlwaysOnTop(true); 
     window.setVisible(true); 

     // This works: 
     window.getRootPane().addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseClicked(MouseEvent e) { 
      window.setVisible(false); 
      } 
     }); 

     // This does not work: 
     window.getRootPane().addKeyListener(new KeyAdapter() { 
      @Override 
      public void keyPressed(KeyEvent e) { 
      System.out.println("key pressed!"); 
      window.setVisible(false); 
      } 
     }); 
     } 
    });  

    panel.add(button); 
    add(panel); 
    } 

    public static void main(String[] args) { 
    HelloSwing hello = new HelloSwing(); 
    hello.setTitle("Title!"); 
    hello.setSize(300, 200); 
    hello.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    hello.setVisible(true); 
    } 
} 

回答

3

爲了要成爲焦點,並具有焦點。關鍵偵聽器是一個較低級別的接口。最好使用Key Bindings來代替。有關詳細信息和示例,請參見How to Use Key Bindings。例如嘗試以下操作:

getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "ESCAPE"); 
getRootPane().getActionMap().put("ESCAPE", new AbstractAction() { 
    public void actionPerformed(ActionEvent e) { 
     window.setVisible(false); 
    } 
}); 

注意ToolTipManager已經註冊VK_ESCAPE隱藏工具提示,在正常情況下逃生按預期工作。

另請注意,在這種情況下不需要使用JToolTip,因爲您正在使用JWindow來手動顯示它。它可以簡單地是一個JLabel

有關常用工具提示使用的一些示例,請參見How to Use Tool Tips

+1

感謝您的幫助;這很好用! – MarkP

+0

@MarkP不客氣!我很高興它幫助:) – tenorsax