gpt4 book ai didi

java - 按下 "enter"键后添加到 JList

转载 作者:行者123 更新时间:2023-12-01 13:36:53 24 4
gpt4 key购买 nike

我只是想做的是在按回车键之前不要将项目添加到 JList,因为我创建了一个类似 Google 的搜索框。我认为这是组合框没有“读取”“输入”键。

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);
}
}

最佳答案

为此,我建议您使用 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();
}

}

关于java - 按下 "enter"键后添加到 JList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21206679/

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