Issue
I created this method:
public void comboS() {
ResultSet rset = null;
String sch = ((JTextField) ComboItemName.getEditor().getEditorComponent()).getText();
try {
rset = new JDBC.DB().getData("SELECT * FROM item_reg WHERE id LIKE '" + sch + "%';");
} catch (Exception e) {
System.out.println(e);
}
ComboItemName.removeAllItems();
try {
while (rset.next()) {
String item = rset.getString("id");
ComboItemName.addItem(item);
}
} catch (SQLException ex) {
Logger.getLogger(jfilechooser.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
ComboItemName.setSelectedItem(null);
ComboItemName.setPopupVisible(true);
((JTextField) ComboItemName.getEditor().getEditorComponent()).setText(sch);
}
I call this method in actionPerformed of the JComboBox(ComboItemName)..When I type HDD and hit enter it shows all the ids of hard disks in database..But I want this to be appear while I typing HDD.I think for that a keyEvent should be apply to the method like this.
public void comboS(java.awt.event.KeyEvent evt)
But I don't know how to call this method and where in combo box.give me some help for this.thanks. Like this
Solution
Use DocumentListener
on your editor component for that purposes, here is example with that:
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class Example extends JFrame {
public Example() {
JComboBox comboBox = new JComboBox(new String[]{"1","2"});
comboBox.setEditable(true);
((JTextComponent)comboBox.getEditor().getEditorComponent()).getDocument().addDocumentListener(new DocumentListener() {
@Override
public void removeUpdate(DocumentEvent arg0) {
validateHDD(arg0);
}
@Override
public void insertUpdate(DocumentEvent arg0) {
validateHDD(arg0);
}
@Override
public void changedUpdate(DocumentEvent arg0) {
validateHDD(arg0);
}
private void validateHDD(DocumentEvent arg0) {
try {
String text = arg0.getDocument().getText(0, arg0.getDocument().getLength());
if(text.equals("HDD")){
System.out.println("HDD entered");
//call your method here
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
});
add(comboBox);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Example frame = new Example();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
validateHDD
validate if you entered HDD into editor of JComboBox
, and then executes some logic if it is true.
Answered By - alex2410
Answer Checked By - Pedro (JavaFixing Volunteer)