似乎只是正常工作對我來說...
單擊第二個文本字段,你應該看到的焦點丟失事件火災。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestFocus {
public static void main(String[] args) {
new TestFocus();
}
public TestFocus() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
add(new JScrollPane(new JDynamicTextArea()));
add(new JTextField(10));
}
}
protected class JDynamicTextArea extends JTextArea implements FocusListener {
public JDynamicTextArea() {
super(10, 10);
addFocusListener(this);
}
public void focusGained(FocusEvent e) {
System.out.println("Focus gained");
}
public void focusLost(FocusEvent e) {
System.out.println("Focus lost");
}
}
}
與重點轉移
要重新啓用鍵盤轉移焦點更新,則需要添加以下構造
Set<KeyStroke> strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("pressed TAB")));
setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, strokes);
strokes = new HashSet<KeyStroke>(Arrays.asList(KeyStroke.getKeyStroke("shift pressed TAB")));
setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, strokes);
你有沒有註冊類爲使用addFocusListener一個焦點偵聽器? – MadProgrammer 2013-03-26 09:16:27
是的,我已經在構造函數中添加了焦點偵聽器。 – eatSleepCode 2013-03-26 09:17:17
我想你需要提供示例代碼然後 – MadProgrammer 2013-03-26 09:17:49