1

我在 Swing 应用程序中实现 autocompleteDecorator。我的代码是这样的。

public inventory_purchase() {
    initComponents();
    AutoCompleteDecorator.decorate(this.combo);
}

public void autocomplete(){
    try{
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        Connection conn= DriverManager.getConnection("jdbc:derby://localhost:1527/C:/jpublisher/pub", "APP", "app");
        Statement stmt = conn.createStatement();
        String query="SELECT * FROM INVENTORY";
        ResultSet rs = stmt.executeQuery(query);
        while(rs.next()){
            combo.addItem(rs.getString("CATEGORY"));
        }
    }
    catch ( ClassNotFoundException | SQLException ex) {
        JOptionPane.showMessageDialog(null, "Data cannot be loaded. Error!!");
    }   

}

这个自动完成装饰器只有在我调用这个函数时才起作用

formWindowOpened(java.awt.event.WindowEvent evt){autocomplete();} 

如何将此自动完成功能与关键侦听器一起使用?喜欢 :

private void comboKeyReleased(java.awt.event.KeyEvent evt) {
    autocomplete();
}

是否有任何其他简单的过程可以使用数据库中的自动完成功能?

4

1 回答 1

1

您可能想使用Key Bindings。这是一个简单的例子:

import java.awt.event.*;
import javax.swing.*;

public class KeyBindings extends Box{
    public KeyBindings(){
        super(BoxLayout.Y_AXIS);

        final JLabel text = new JLabel("Original Text");
        add(text);

        Action action = new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                text.setText("New Text");
            }};
         String keyStrokeAndKey = "control H";
         KeyStroke keyStroke = KeyStroke.getKeyStroke(keyStrokeAndKey);
         getInputMap().put(keyStroke, keyStrokeAndKey);
         getActionMap().put(keyStrokeAndKey, action);
    }


    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new KeyBindings());
        frame.pack();
        frame.setVisible(true);
    }
}
于 2012-12-19T21:03:40.353 回答