我只是想做的是在我点击输入之前不要将项目添加到JList,因为我创建了一个类似Google的搜索框。我认为这是comboBox没有“读取”“输入”键。
public void count(){
try{
String sql2 = "select count(*) from workers_info";
stmt = conn.prepareStatement(sql2);
rs=stmt.executeQuery();
while(rs.next()){
String x = rs.getString("count(*)");
z = Integer.parseInt(x);
}
auto = new String[z];
}
catch(SQLException | NumberFormatException e){
}
}
public void cB(){
try{
String sql = "Select concat(first_name, ' ',last_name) as full_name from workers_info";
stmt = conn.prepareStatement(sql);
rs=stmt.executeQuery();
while(rs.next()){
String name = rs.getString("full_name");
auto[i] = name;
i++;
}
AutoCompleteSupport a = AutoCompleteSupport.install(comboSearch, GlazedLists.eventListOf(auto));
a.setStrict(false);
comboSearch.isEditable();
}
catch(SQLException e){
}
}
//this actually is my main concern..why it cant detect when i hit "enter" key?
private void comboSearchKeyPressed(java.awt.event.KeyEvent evt) {
String s1 = (String)comboSearch.getSelectedItem();
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
model.addElement(s1);
workerList.setModel(model);
comboSearch.setSelectedItem(null);
}
}
答案 0 :(得分:1)
为此,我建议您使用Key bindings而不是KeyListener。试试下一个简单的例子:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
public class Example extends JFrame{
private JComboBox<String> comboBox;
private JList<String> list;
private DefaultListModel<String> model;
Example(){
comboBox = new JComboBox<>(new String[]{"111","222","333"});
list = new JList<>(model = new DefaultListModel<>());
add(comboBox,BorderLayout.SOUTH);
add(new JScrollPane(list));
addKeyBindings((JComponent) getContentPane());
addKeyBindings(comboBox);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
private void addKeyBindings(JComponent c) {
c.getInputMap(JComboBox.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke("ENTER"), "doSomething");
c.getActionMap().put("doSomething", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
Object selectedItem = comboBox.getSelectedItem();
if(selectedItem != null){
model.addElement((String)selectedItem);
}
}
});
}
public static void main(String[] args) {
new Example();
}
}