自动完成装饰器

时间:2012-12-19 18:18:02

标签: java swing autocomplete decorator swingx

我正在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();
}

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

1 个答案:

答案 0 :(得分: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);
    }
}