问题描述:

I am implementing autocompleteDecorator in a Swing application. My codes are like this.

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!!");

}

}

This Autocomplete Decorator works only when I call this function in

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

How can I use this autocomplete with a key listener? Like :

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

autocomplete();

}

Is there any other simple process to use autocomplete from database?

网友答案:

You probably want to use Key Bindings. Here's a quick example:

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);
    }
}
相关阅读:
Top