【Java】 JTextField文字框實時監控
阿新 • • 發佈:2019-02-01
最近在做課程設計,有遇到一個想法,就是在JTextField文字框輸入資料的時候實時判斷這個資料在資料庫中能不能找到對應的記錄。
如果有顯示在螢幕上,沒有的話不顯示資訊。
查閱API後得知需要JTextField中的getDocument()函式,為這個方法新增文字監聽器addDocumentListener,這個監聽器下有三個自動寫好的方法insertUpdate(),removeUpdate(),changedUpdate(),分別能夠實現插入更新、刪除更新、更改文字的監聽。
由於JTextField中的文字只限於上述這三種形式的改變,因此通過getDocument()方法再增添此種監聽器可以實現JTextField文字框輸入資料的實時判斷功能。
以下列出程式碼舉例。
textField_1.getDocument().addDocumentListener (new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub ResultSet rs = new DBOperation().dbope("select 型別 from 利率單 where 編號='"+textField_1.getText().trim()+"'"); try { if(rs.next()) { textArea_1_show.setText(rs.getString(1)); } else { textArea_1_show.setText(""); } } catch (SQLException e1) { // TODO Auto-generated catch block //e1.printStackTrace(); textArea_1_show.setText("編號有誤"); } } @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub ResultSet rs = new DBOperation().dbope("select 型別 from 利率單 where 編號='"+textField_1.getText().trim()+"'"); try { if(rs.next()) { textArea_1_show.setText(rs.getString(1)); } else { textArea_1_show.setText(""); } } catch (SQLException e1) { // TODO Auto-generated catch block //e1.printStackTrace(); textArea_1_show.setText("編號有誤"); } } @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub ResultSet rs = new DBOperation().dbope("select 型別 from 利率單 where 編號='"+textField_1.getText().trim()+"'"); //資料庫連線,SQL語句實參傳入形參str執行dbope(String str)方法. try { if(rs.next()) { textArea_1_show.setText(rs.getString(1)); } else { textArea_1_show.setText(""); } } catch (SQLException e1) { // TODO Auto-generated catch block //e1.printStackTrace(); textArea_1_show.setText("編號有誤"); } } });
以上程式碼實現實時監控(JTextField)textField_1中的文字,連線資料庫查詢是否存在該文字輸入的資料作為編號在利率單中所對應的型別。若存在該型別則在下面的JTextArea中輸出,否則顯示為空。
執行結果如上。Eclipse-Java Mars、JDK1.8實測通過。