0

にフォーカスを設定する方法があるかどうか知りたいですJLabel。一連のラベルがあり、それらのいずれかが選択されているかどうかを知りたいです。

私は a を使用すると思いますMouseListenerが、フォーカスを設定するためにどの属性JLabelが使用されているのか、またはそのラベルを選択しているモードで言っているのかわかりません。

みなさん、ありがとうございます。下手な英語で申し訳ありません。

4

2 に答える 2

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);
            }
        });
    }
}
于 2013-06-21T01:33:34.550 に答える