0

クライアント名を格納するMySQLテーブル「pessoa」から自動提案を作成するためにそこにをJFrame Principal.java置きました。JComboBoxこの作業コードを実装する方法:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package teste;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

/**
 *
 * @author Marcio
 */
public class AutoSuggest extends javax.swing.JFrame {

    public AutoSuggest() {
    initComponents();

    final JTextField textfield = (JTextField) jComboBox1.getEditor().getEditorComponent();
    textfield.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent ke) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    comboFilter(textfield.getText());
                }
            });
        }
    });
}



public void comboFilter(String enteredText) {
    List<String> filterArray= new ArrayList<String>();

            String str1="";

     try
    {


    String str="SELECT * FROM pessoa WHERE nome LIKE '"+enteredText+"%'";

     Class.forName("com.mysql.jdbc.Driver");
     Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "");
     Statement stmt=con.createStatement();
     ResultSet rs=stmt.executeQuery(str);
     while(rs.next())
     {

      str1=rs.getString("nome");
      filterArray.add(str1);


     }

    }
    catch(Exception ex)
    {
     System.out.println("error"+ex);   
    }




    if (filterArray.size() > 0) {
        jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray()));
        jComboBox1.setSelectedItem(enteredText);
        jComboBox1.showPopup();
    }
    else {
        jComboBox1.hidePopup();
    }
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jComboBox1 = new javax.swing.JComboBox();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jComboBox1.setEditable(true);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(87, 87, 87)
            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(98, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(108, 108, 108)
            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(172, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new AutoSuggest().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
// End of variables declaration
} 

Principal.java のメイン画面に移動します。

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

    final JTextField textfield = (JTextField) jComboBox1.getEditor().getEditorComponent();
    textfield.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent ke) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    comboFilter(textfield.getText());
                }
            });
        }
    });

}                                          


public void comboFilter(String enteredText) {
    List<String> filterArray = new ArrayList<String>();

    String str1 = "";

    try {

        String str = "SELECT * FROM pessoa WHERE nome LIKE '" + enteredText + "%'";

        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", "");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(str);
        while (rs.next()) {

            str1 = rs.getString("nome");
            filterArray.add(str1);

        }

    } catch (Exception ex) {
        System.out.println("error" + ex);
    }

    if (filterArray.size() > 0) {
        jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray()));
        jComboBox1.setSelectedItem(enteredText);
        jComboBox1.showPopup();
    } else {
        jComboBox1.hidePopup();
    }
}
4

1 に答える 1

0

roseindiaの以下の作業コードを参照できます。これがあなたが探しているものであることを願っています。

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

public class AutoSuggest extends JPanel{
    private final JTextField tf;
    private final JComboBox combo = new JComboBox();
    private final Vector<String> v = new Vector<String>();
    public AutoSuggest() {
        super(new BorderLayout());
        combo.setEditable(true);
        tf = (JTextField) combo.getEditor().getEditorComponent();
        tf.addKeyListener(new KeyAdapter() {
                public void keyTyped(KeyEvent e) {
               EventQueue.invokeLater(new Runnable() {
            public void run() {
                String text = tf.getText();
                        if(text.length()==0) {
                    combo.hidePopup();
                    setModel(new DefaultComboBoxModel(v), "");
                }else{
                    DefaultComboBoxModel m = getSuggestedModel(v, text);
                    if(m.getSize()==0 || hide_flag) {
                          combo.hidePopup();
                        hide_flag = false;
                    }else{
                        setModel(m, text);
                        combo.showPopup();
                    }
                }
            }
        });
            }
                public void keyPressed(KeyEvent e) {
               String text = tf.getText();
         int code = e.getKeyCode();
             if(code==KeyEvent.VK_ENTER) {
            if(!v.contains(text)) {
                v.addElement(text);
                Collections.sort(v);
                setModel(getSuggestedModel(v, text), text);
            }
            hide_flag = true; 
        }else if(code==KeyEvent.VK_ESCAPE) {
            hide_flag = true; 
        }else if(code==KeyEvent.VK_RIGHT) {
            for(int i=0;i<v.size();i++) {
                String str = v.elementAt(i);
                if(str.startsWith(text)) {
                    combo.setSelectedIndex(-1);
                    tf.setText(str);
                    return;
                }
            }
        }
            }
      });
        String[] countries = {"Afghanistan", "Albania", "Algeria", "Andorra", "Angola","Argentina"
,"Armenia","Austria","Bahamas","Bahrain", "Bangladesh","Barbados", "Belarus","Belgium",
"Benin","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","Bulgaria",
"Burkina Faso","Burma","Burundi","Cambodia","Cameroon","Canada", "China","Colombia",
"Comoros","Congo","Croatia","Cuba","Cyprus","Czech Republic","Denmark", "Georgia",
"Germany","Ghana","Great Britain","Greece","Hungary","Holland","India","Iran","Iraq",
"Italy","Somalia", "Spain", "Sri Lanka", "Sudan","Suriname", "Swaziland","Sweden",
"Switzerland", "Syria","Uganda","Ukraine","United Arab Emirates","United Kingdom",
"United States","Uruguay","Uzbekistan","Vanuatu","Venezuela","Vietnam",
"Yemen","Zaire","Zambia","Zimbabwe"};
          for(int i=0;i<countries.length;i++){
                  v.addElement(countries[i]);
          }
        setModel(new DefaultComboBoxModel(v), "");
        JPanel p = new JPanel(new BorderLayout());
        p.setBorder(BorderFactory.createTitledBorder("AutoSuggestion Box"));
        p.add(combo, BorderLayout.NORTH);
        add(p);
        setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        setPreferredSize(new Dimension(300, 150));
    }
    private boolean hide_flag = false;
       private void setModel(DefaultComboBoxModel mdl, String str) {
        combo.setModel(mdl);
        combo.setSelectedIndex(-1);
        tf.setText(str);
    }
private static DefaultComboBoxModel getSuggestedModel(java.util.List<String> list, String text) {
        DefaultComboBoxModel m = new DefaultComboBoxModel();
        for(String s: list) {
            if(s.startsWith(text)) m.addElement(s);
        }
        return m;
    }
    public static void main(String[] args) {
       JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new AutoSuggest());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    }
于 2013-11-05T02:53:09.313 に答える