2013-06-20 54 views
0

我想知道是否有任何方法将重点放在我的JLabel上。 我有一系列的标签,我想知道我是否选择了其中任何一个。鼠标焦点在JLabel

我想使用MouseListener,但不知道JLabel的什么属性用于设置焦点或在某些模式下说我选择了该标签。

谢谢大家,对不起我的英文不好。

+0

你想设置**焦点还是要检测**焦点? –

+0

我想检测是否有人点击我的标签 – Rotom92

+0

使用Jlabel.addMouseListener(....)进行测试。 – Chuidiang

回答

0

要检测是否有人在标签上点击,这个代码将工作:

package com.sandbox; 

import javax.swing.BoxLayout; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.WindowConstants; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 

public class SwingSandbox { 

    public static void main(String[] args) { 
     JFrame frame = buildFrame(); 

     JPanel panel = new JPanel(); 
     BoxLayout layout = new BoxLayout(panel, BoxLayout.X_AXIS); 
     panel.setLayout(layout); 
     frame.getContentPane().add(panel); 

     JLabel label = new JLabel("Click me and I'll react"); 
     label.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseClicked(MouseEvent e) { 
       System.out.println("clicked!"); 
      } 
     }); 
     panel.add(label); 
     panel.add(new JLabel("This label won't react")); 
    } 


    private static JFrame buildFrame() { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     frame.setSize(200, 200); 
     frame.setVisible(true); 
     return frame; 
    } 


} 
+0

label.setSize()是什么意思?无论如何,布局经理都会忽略它。 – camickr

+0

@camickr那是因为“历史”原因。我将删除该行。 –

0

您可以添加FocusListenerJLabel这样,每当它接收的焦点,它的听众将得到通知。这是一个样本测试。

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.FocusAdapter; 
import java.awt.event.FocusEvent; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 

public class JLabelFocusTest { 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run() { 
       JFrame frame = new JFrame("Demo"); 

       frame.getContentPane().setLayout(new BorderLayout()); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

       final JLabel lblToFocus = new JLabel("A FocusEvent will be fired if I got a focus."); 
       JButton btnFocus = new JButton("Focus that label now!"); 

       btnFocus.addActionListener(new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent arg0) { 
         lblToFocus.requestFocusInWindow(); 
        } 
       }); 

       lblToFocus.addFocusListener(new FocusAdapter() { 
        @Override 
        public void focusGained(FocusEvent e) { 
         super.focusGained(e); 

         System.out.println("Label got the focus!"); 
        } 
       }); 

       frame.getContentPane().add(lblToFocus, BorderLayout.PAGE_START); 
       frame.getContentPane().add(btnFocus, BorderLayout.CENTER); 

       frame.pack(); 
       frame.setVisible(true); 
      } 
     }); 
    } 
}