JCombobox獲取可編輯之後的值
效果圖:
一:swing中獲取下拉列表編輯後的值
jComboBox.getEditor().getItem().toString();
注:jComboBox.getSelectedItem().toString().trim();只能獲取到上一次選中的值,獲取不到編輯後的值,只有當光標移除的時候,這時點擊按鈕就可以獲取編輯後的值,但實際中是不可以的,所有就要用到jComboBox.getEditor().getItem().toString();獲取值的方法,它可以獲取編輯的值。
二:swing中獲取選中的值
jComboBox.getSelectedItem().toString().trim();
上面圖片示例的完整代碼如下:
public class EditJCombobox extends JFrame {
private static final long serialVersionUID = 1L;
private final String[] ITEMS = new String[] { "ITEM1", "ITEM2" };
private JComboBox comBox = new JComboBox(ITEMS);
private JButton btn = new JButton("提交");
private JTextField inputTxt = new JTextField(15);
public EditJCombobox() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("JComboBox測試");
// 返回組合框編輯器的樹層次結構中的組件
Component editorComponent = comBox.getEditor().getEditorComponent();
editorComponent.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent evt) {
String strItem = comBox.getEditor().getItem().toString();
if (strItem.isEmpty())
btn.setEnabled(false);
else
btn.setEnabled(true);
inputTxt.setText(strItem);
}
});
comBox.setEditable(true);
this.add(comBox, "Center");
JPanel btnPanel = new JPanel();
btnPanel.add(btn);
btnPanel.add(inputTxt);
this.add(btnPanel, "South");
this.pack();
}
public static void main(String[] args) {
EditJCombobox main = new EditJCombobox();
main.setVisible(true);
}
}