JLabelがクリックされたらこれに割り当てられているコンポーネントにフォーカスを移動する
Total: 3700
, Today: 3
, Yesterday: 5
Posted by aterai at
Last-modified:
Summary
JLabel
がマウスでクリックされたらこのラベルに割り当てられているコンポーネントにフォーカスを移動します。
Screenshot

Advertisement
Source Code Examples
MouseListener focusHandler = new MouseAdapter() {
@Override public void mouseClicked(MouseEvent e) {
Component c = ((JLabel) e.getComponent()).getLabelFor();
if (c != null) {
c.requestFocusInWindow();
}
}
};
JLabel label1 = new JLabel("Mail Address:", SwingConstants.RIGHT);
label1.addMouseListener(focusHandler);
label1.setDisplayedMnemonic('M');
Component textField1 = new JTextField(12);
label1.setLabelFor(textField1);
View in GitHub: Java, KotlinExplanation
JLabel#setLabelFor(...)
メソッドでJLabel
にコンポーネントを割り当てるとニーモニックがアクティブになったときそのコンポーネントにフォースが移動する- 上記のサンプルでは
JLabel
にMouseListener
を追加してマウスでJLabel
がクリックされた場合も同様にフォースを割り当てられたコンポーネントに移動するよう設定