gpt4 book ai didi

java - 如何使 JComboBox 的弹出菜单可见?

转载 作者:行者123 更新时间:2023-12-01 08:57:56 24 4
gpt4 key购买 nike

如何使可编辑 JComboBox 的弹出菜单可见?当我在 JComboBox 的文本字段中输入任何文本时,它应该显示其弹出列表项。这是我的代码。我添加了一个 KeyListener,在其中调用 showPopup() 和 setPopupVisible(true)。但它什么也没做。

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Test extends JFrame {

private JPanel contentPane;
private JComboBox comboBox;
private JTextField textField;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
public Test() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

comboBox = new JComboBox(new Object[] {"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});
comboBox.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
comboBox.showPopup();
comboBox.setPopupVisible(true);
}
});
comboBox.setEditable(true);
comboBox.setBounds(10, 11, 414, 20);
contentPane.add(comboBox);
}
}

最佳答案

我做了一些工作并以某种方式使其发挥作用。但这不是推荐的方式。请在后面添加以下代码

comboBox = new JComboBox(new Object[] {"Ester", "Jordi", "Jordina", "Jorge", "Sergi"});

Component[] comps = comboBox.getComponents();
for(Component comp : comps){
if(comp instanceof CellRendererPane){
JComboBox co = (JComboBox) ((CellRendererPane)comp).getParent();
co.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent arg0) {
comboBox.showPopup();
comboBox.setPopupVisible(true);
}
});
}
}

这工作正常。但最好使用装饰器并拥有新组件,另请参阅以下文章,

JComboBox autocomplete

关于java - 如何使 JComboBox 的弹出菜单可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com