I can't figure out how to implement a focus listener on a comboxbox. I understand that it is not a simple thing to do, yet other people seem to have gotten it to work[1][2][3], yet I am unable to duplicate their results after carefully examining each one. After extensive searching all over the web, checking the latest Oracle guide, Oracle documentation, etc., I've come here. My question is simply:
我无法弄清楚如何在comboxbox上实现焦点监听器。我知道这不是一件简单的事情,但是其他人似乎已经开始工作了[1] [2] [3],但是在仔细检查每一个之后我无法复制他们的结果。经过网络上的广泛搜索,查看最新的Oracle指南,Oracle文档等,我来到这里。我的问题很简单:
Is it possible to add focus listeners to comboboxes and if so how?
The goal is to create a field basically identical to Google search. You can type in a search query, and it will populate a dropdown below the text field with possible search matches. If all else fails I'll just have both a comboxbox and a textfield on top of each other and setup some sort of elaborate visibility toggling, but I would prefer not to...
目标是创建一个与Google搜索基本相同的字段。您可以输入搜索查询,它将填充文本字段下方的下拉列表,并显示可能的搜索匹配项。如果所有其他方法都失败了,我将只有一个comboxbox和一个文本字段在彼此之上,并设置一些精细的可见性切换,但我宁愿不...
Using:
Java 1.7.0_21 (← side note: why do I have to escape this underscore to italicize this text? What does underscore do?)
Windows 7 x64
使用:Java 1.7.0_21(←旁注:为什么我必须通过这个下划线来斜体化这个文本?下划线做什么?)Windows 7 x64
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.JTextField;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
public class focustest extends JFrame {
private JPanel contentPane;
private JTextField textField;
public focustest theframe;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
focustest theframe = new focustest();
theframe.setVisible(true);
}
});
}
public focustest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 106);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JComboBox comboBox = new JComboBox();
comboBox.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent arg0) {
JOptionPane.showMessageDialog(theframe, "focus gained!", null,JOptionPane.PLAIN_MESSAGE);
}
@Override
public void focusLost(FocusEvent arg0) {
JOptionPane.showMessageDialog(theframe, "focus lost!", null,JOptionPane.PLAIN_MESSAGE);
}
});
comboBox.setEditable(true);
contentPane.add(comboBox, BorderLayout.NORTH);
textField = new JTextField();
contentPane.add(textField, BorderLayout.SOUTH);
textField.setColumns(10);
}
}
1 个解决方案
#1
3
comboBox.getEditor().getEditorComponent().addFocusListener(new FocusAdapter() {
// ....
}
and good luck with that.
祝你好运
#1
3
comboBox.getEditor().getEditorComponent().addFocusListener(new FocusAdapter() {
// ....
}
and good luck with that.
祝你好运