如何选择JComboBox在JTextfield中选择的项目?

时间:2018-06-13 13:08:26

标签: java jtextfield jcombobox

我通过文字字段编写了搜索人名的小程序,因为我可以在手机通讯录中搜索。

我在组合框中放了5个名字,当我搜索'a'然后它显示所有5个名字因为每个都有字符'a',然后我用鼠标选择第3或第4个名字,那么它应该在Text字段中显示我在哪里写了'a'。

每次将文本字段中的“a”替换为组合框中的第一个名称,我想写第二个,第三个字符,或者从组合框中的下拉列表中选择。

但我不能这样做。

这里参考我的程序

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;

class SearchName extends JFrame {

    private static final long serialVersionUID = -3725136550174445695L;
    private final JPanel contentPane;
    private JTextField textField;
    private static JComboBox<Object> comboBox;
    private static final List<String> name_list = Arrays.asList("RAM", "Abraham", "Adam", "Dawson", "Elisha");
    private final Object[] nameArray = name_list.toArray();
    private static final String specailcharacter = "[^a-zA-Z0-9]";

    public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
        try {
            SearchName frame = new SearchName();
            frame.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        }
    });
    }

    public SearchName() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);
    textField = new JTextField();
    textField.setBounds(10, 26, 297, 20);
    contentPane.add(textField);
    textField.setColumns(10);
    JButton btnNewButton = new JButton("Search");
    btnNewButton.setBounds(317, 25, 89, 23);
    contentPane.add(btnNewButton);
    comboBox = new JComboBox<Object>();
    comboBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
        myBox(evt);
        }
    });
    comboBox.setVisible(true);
    comboBox.setOpaque(false);
    comboBox.setBorder(new LineBorder(new Color(171, 173, 179)));
    comboBox.setMaximumRowCount(20);
    comboBox.setBackground(Color.WHITE);
    comboBox.setBounds(10, 46, 297, 20);
    contentPane.add(comboBox);
    textField.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent arg0) {
        if (arg0 != null) {
            if (arg0.getSource() != null) {
            txtPassKeyTyped(arg0);
            }
        }
        }
    });
    }

    protected void myBox(ActionEvent evt) {
    if (comboBox.getSelectedItem() != null) {
        textField.setText(comboBox.getSelectedItem().toString());
    }
    }

    private void txtPassKeyTyped(KeyEvent arg0) {
    if (arg0 != null) {
        if (arg0.getSource() != null) {
        clear();
        if (comboBox.getItemCount() == 0) {
            textField = (JTextField) arg0.getSource();
            if (textField != null) {
            if (textField.getText() != null) {
                if (!textField.getText().isEmpty()) {
                search(textField.getText(), "name", nameArray.length, nameArray);
                try {
                    comboBox.showPopup();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                comboBox.setMaximumRowCount(20);
                }
            }
            }
        }
        }
    }

    }

    private void clear() {
    if (comboBox.getItemCount() > 0) {
        comboBox.removeAllItems();
        comboBox.setMaximumRowCount(0);
        comboBox.hidePopup();
    }
    }

    private static void search(String searchString, String type, int numberOfContacts, Object[] contacts) {
    if (searchString != null) {
        if (!searchString.isEmpty()) {
        int found = 0;
        int[] results = new int[numberOfContacts];
        Checker c = null;
        if (type.equals("name")) {
            c = new Checker() {
            public boolean check1(Object p, String searchString) {
                boolean a = false;
                if (p.toString().toLowerCase().replaceAll(specailcharacter, "").contains(searchString)) {
                a = true;
                } else if (p.toString().toUpperCase().replaceAll(specailcharacter, "")
                    .contains(searchString)) {
                a = true;
                } else if (p.toString().replaceAll(specailcharacter, "").contains(searchString)) {
                a = true;
                } else {
                a = false;
                }
                return a;
            }
            };
        }
        for (int x = 0; x < numberOfContacts; x++) {
            if (c != null) {
            if (c.check1(contacts[x], searchString)) {
                results[found] = x;
                found++;
            }
            }
        }
        if (found > 0) {
            for (int x = 0; x < found; x++) {
            comboBox.addItem(contacts[results[x]]);
            comboBox.revalidate();
            comboBox.repaint();
            }
        }
        }
    }
    }

    private static interface Checker {
    public boolean check1(Object p, String searchString);
    }
}

1 个答案:

答案 0 :(得分:1)

键入完成后,您必须以某种方式重置文本 将搜索文本存储在变量initialText中,当键入完成并触发侦听器时,将其重置为此初始值。

private void txtPassKeyTyped(KeyEvent arg0) {
    if (arg0 != null) {
      if (arg0.getSource() != null) {
        clear();
        if (comboBox.getItemCount() == 0) {
          textField = (JTextField) arg0.getSource();
          if (textField != null) {
            String initialText = textField.getText();
            if (textField.getText() != null) {
              if (!textField.getText().isEmpty()) {
                search(textField.getText(), "name", nameArray.length, nameArray);
                try {
                  comboBox.showPopup();
                } catch (Exception e1) {
                  e1.printStackTrace();
                }
                comboBox.setMaximumRowCount(20);
              }
            }
            textField.setText(initialText);
          }
        }
      }
    }
  }