这是我的第一个问题,我真的很抱歉我的英语。我不想在JComboBox的下拉列表中导航,显示" JComboBox主要字段中的所选项目" (对不起,不知道怎么称呼它,看图像)。
当我在列表中导航时会发生这种情况:
但我想要这样的事情:
当我按Enter或点击项目时,它会出现在主要字段中。
这是我的代码:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
public class ComboTest {
JFrame frame;
JPanel panel;
String[] choices = new String[]{
"Java",
"Python",
"C++",
"PHP",
"Perl"
};
JComboBox<String> comboBox = new JComboBox<>(choices);
JTextComponent textComponent;
public static void main(String[] args){
new ComboTest();
}
public ComboTest() {
frame = new JFrame();
panel = new JPanel();
textComponent = (JTextComponent) comboBox.getEditor().getEditorComponent();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 150);
frame.setResizable(false);
panel.setLayout(new FlowLayout());
comboBox.setEditable(true);
comboBox.setSelectedItem(null);
panel.add(comboBox);
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
答案 0 :(得分:1)
试试此代码块
comboBox.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
//when Popupmenu is visible, remove the combobox editor text
comboBox.getEditor().setItem(null);
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
答案 1 :(得分:0)
感谢zilk。你的回答帮我解决了这个问题。听众addPopupMenuListener
对我不起作用。但当我将addPopupMenuListener
更改为addItemListener
时,一切正常。
comboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(final ItemEvent itemEvent) {
comboBox.getEditor().setItem(null);
comboBox.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if(e.getKeyCode() == KeyEvent.VK_ENTER)
{
comboBox.getEditor().setItem(itemEvent.getItem());
}
}
});
}
});