List of usage examples for javax.swing JTextField setSelectionStart
@BeanProperty(bound = false, description = "starting location of the selection.") public void setSelectionStart(int selectionStart)
From source file:Main.java
public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JButton button = new JButton("Click me"); button.addActionListener(e -> {//www. j av a 2 s.co m JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(new File(chooser.getCurrentDirectory(), "save.dat")); final JTextField textField = getTexField(chooser); if (textField == null) { return; } String text = textField.getText(); if (text == null) { return; } int index = text.lastIndexOf('.'); if (index == -1) { return; } textField.setSelectionStart(0); textField.setSelectionEnd(index); chooser.showSaveDialog(button); }); frame.add(button); frame.pack(); frame.setVisible(true); }
From source file:Main.java
public static void selectField(JTextField jtf) { jtf.setSelectionStart(0); jtf.setSelectionEnd(jtf.getText().length()); }
From source file:Main.java
/** * Select all text in a {@link JComponent} if it is a {@link JTextField} or {@link JTextArea}. * * @param comp the component// w w w . j ava2s . com */ public static void selectAllText(JComponent comp) { if (comp instanceof JTextField) { JTextField tf = (JTextField) comp; tf.setSelectionStart(0); tf.setSelectionEnd(tf.getText().length()); } else if (comp instanceof JTextArea) { JTextArea ta = (JTextArea) comp; ta.setSelectionStart(0); ta.setSelectionEnd(ta.getText().length()); } }
From source file:Main.java
public static void focusAndSelectTextInTextField(JTextField textField) { int length = textField.getText().length(); textField.setSelectionStart(0); textField.setSelectionEnd(length);//from w w w . ja v a 2 s . c o m textField.requestFocus(); }
From source file:Main.java
/** * Same as {@link #requestFocus(Component)} but also selects all text in the text-field. */// w w w . j ava2 s . co m public static void requestFocusSelectAll(final JTextField c) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { c.requestFocusInWindow(); int l = c.getDocument().getLength(); if (l > 0) { c.setSelectionStart(0); c.setSelectionEnd(l); } } }); }
From source file:edu.ku.brc.specify.ui.DBObjSearchPanel.java
/** * @param comp/* w ww .j av a 2 s. c om*/ */ protected void doStartQuery(final JComponent comp) { getDataFromUI(); QueryForIdResultsIFace resultsInfo = null; if (queryBuilder != null) { sqlStr = queryBuilder.buildSQL(dataMap, fieldNames); if (StringUtils.isNotEmpty(sqlStr)) { resultsInfo = queryBuilder.createQueryForIdResults(); if (resultsInfo != null) { resultsInfo.setSQL(sqlStr); resultsInfo.setMultipleSelection(isMultipleSelection); } } else { UIRegistry.getStatusBar().setLocalizedErrorMessage("ES_SUSPICIOUS_SQL"); return; } } else { QueryAdjusterForDomain qafd = QueryAdjusterForDomain.getInstance(); StringBuilder strBuf = new StringBuilder(256); int cnt = 0; for (ERTICaptionInfo captionInfo : esTableInfo.getVisibleCaptionInfo()) { String colName = null; Object value = null; if (captionInfo.getColName() == null) { for (ColInfo colInfo : captionInfo.getColInfoList()) { colName = colInfo.getColumnName(); log.debug("colInfo - colInfoColumn Name[" + colName + "]"); value = dataMap.get(colName); if (value != null) { log.debug("Column Name[" + colName + "][" + captionInfo.getColLabel() + "] [" + captionInfo.getFieldInfo() + "] Value[" + value + "]"); break; } } } else { colName = captionInfo.getColName(); value = StringUtils.isNotEmpty(colName) ? dataMap.get(captionInfo.getColName()) : null; log.debug("Column Name[" + colName + "][" + captionInfo.getColLabel() + "] [" + captionInfo.getFieldInfo() + "] Value[" + value + "]"); } if (value != null) { String valStr = value.toString(); if (valStr.length() > 0) { if (qafd.isUserInputNotInjectable(valStr)) { if (ESTermParser.getInstance().parse(valStr.toLowerCase(), true)) { if (StringUtils.isNotEmpty(valStr)) { List<SearchTermField> fields = ESTermParser.getInstance().getFields(); SearchTermField firstTerm = fields.get(0); if (cnt > 0) { strBuf.append(" AND "); } String clause = null; if (captionInfo.getFieldInfo() != null && form instanceof FormViewObj) { FormViewObj fvo = (FormViewObj) form; FormViewObj.FVOFieldInfo fInfo = fvo.getFieldInfoForName(colName); if (fInfo != null) { if (fInfo.getFormCell() != null && fInfo.getFormCell() .getPropertyAsBoolean("ispartial", false)) { if (fInfo.getFormCell() instanceof FormCellFieldIFace) { FormCellFieldIFace cif = (FormCellFieldIFace) fInfo .getFormCell(); String fmt = cif.getUIFieldFormatterName(); if (StringUtils.isNotEmpty(fmt) && fmt.equals("SearchDate")) // XXX There is a better way to check for this (use the enum) { clause = getDateClause(firstTerm, colName); } } if (clause == null) { firstTerm.setTerm(firstTerm.getTermLowerCase()); firstTerm.setOption(SearchTermField.ENDS_WILDCARD); } } } } if (clause == null) { clause = ESTermParser.getInstance().createWhereClause(firstTerm, null, colName); } strBuf.append(clause); cnt++; } } } else { UIRegistry.getStatusBar().setErrorMessage(getResourceString("ES_SUSPICIOUS_SQL")); return; } } } /* else { log.debug("DataMap was null for Column Name["+captionInfo.getColName()+"] make sure there is a field of this name in the form."); }*/ } if (cnt == 0) { return; } String fullStrSql = QueryAdjusterForDomain.getInstance().adjustSQL(sqlStr); String fullSQL = fullStrSql.replace("%s", strBuf.toString()); log.info(fullSQL); setUIEnabled(false); resultsInfo = new QueryForIdResultsSQL(esTableInfo.getId(), null, esTableInfo, 0, ""); resultsInfo.setSQL(fullSQL); resultsInfo.setMultipleSelection(isMultipleSelection); } addSearchResults(resultsInfo); if (comp instanceof JTextField) { final JTextField txt = (JTextField) comp; int len = txt.getText().length(); txt.setSelectionEnd(len); txt.setSelectionStart(0); SwingUtilities.invokeLater(new Runnable() { public void run() { txt.requestFocus(); } }); } }
From source file:edu.ku.brc.af.ui.forms.validation.ValComboBoxFromQuery.java
/** * Updates the UI from the data value (assume the data has changed but OK if it hasn't). * @param useSession indicates it should create a session *///from w ww. j a v a 2 s .co m private void refreshUIFromData(final boolean useSession) { if (this.dataObj != null) { if (getter == null) { getter = new DataGetterForObj(); } // NOTE: If there was a formatName defined for this then the value coming // in will already be correctly formatted. // So just set the value if there is a format name. Object newVal = this.dataObj; if (isEmpty(dataObjFormatterName)) { Object[] val = UIHelper.getFieldValues(fieldNames, this.dataObj, getter); UIFieldFormatterIFace uiFieldFormatter = textWithQuery.getUiFieldFormatter(); if (uiFieldFormatter != null) { if (val != null && val.length > 0 && val[0] != null) { newVal = uiFieldFormatter.formatFromUI(val[0]).toString(); } else { newVal = null; } } else { if (StringUtils.isNotEmpty(textWithQuery.getFormat())) { newVal = UIHelper.getFormattedValue(textWithQuery.getFormat(), val); } else { newVal = this.dataObj; } } } else { DataProviderSessionIFace localSession = null; try { localSession = DataProviderFactory.getInstance().createSession(); newVal = DataObjFieldFormatMgr.getInstance().format(this.dataObj, dataObjFormatterName); if (newVal == null || "".equals(newVal.toString().trim())) { newVal = this.tableInfo.getTitle() + ":" + dataObj.getId(); //fixes bug 10150. Kinder, gentler, more informative text might be preferable. } } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(ValComboBoxFromQuery.class, ex); ex.printStackTrace(); } finally { if (localSession != null) { localSession.close(); } } } if (newVal != null && textWithQuery != null) { valState = UIValidatable.ErrorType.Valid; textWithQuery.setSelectedId(dataObj != null ? dataObj.getId() : null); // needs to be done before and after final JTextField tf = textWithQuery.getTextField(); // rods 08/18/08 - doesn't seem to be needed it is already set correctly // // 02/06/09 - Commented out because it is causing the idList to be cleared // If you turn it back on make sure you turn on ignoreDocChange in the TextFieldWithQuery // // 02/10/09 - rods - Instead of call seTText directly on the TextField, it is called on the TextFieldWithQuery // which disables Doc change notifications textWithQuery.setText(newVal.toString()); SwingUtilities.invokeLater(new Runnable() { public void run() { tf.setSelectionStart(-1); tf.setSelectionEnd(-1); tf.setCaretPosition(0); } }); textWithQuery.setSelectedId(dataObj != null ? dataObj.getId() : null); if (editBtn != null) { editBtn.setEnabled(true); } if (cloneBtn != null) { //cloneBtn.setEnabled(false); cloneBtn.setEnabled(dataObj != null || textWithQuery.getSelectedId() != null); } } else { if (textWithQuery != null) { textWithQuery.clearSelection(); } valState = UIValidatable.ErrorType.Incomplete; } } else { if (textWithQuery != null) { textWithQuery.clearSelection(); } valState = UIValidatable.ErrorType.Incomplete; if (editBtn != null) { editBtn.setEnabled(false); } if (cloneBtn != null) { cloneBtn.setEnabled(false); } if (textWithQuery != null && textWithQuery.getTextField() != null) { textWithQuery.setText(""); textWithQuery.getTextField().repaint(); } } repaint(); }
From source file:op.tools.SYSTools.java
public static void markAllTxt(JTextField jtf) { jtf.setSelectionStart(0); jtf.setSelectionEnd(jtf.getText().length()); }
From source file:org.yccheok.jstock.gui.AutoCompleteJComboBox.java
private DocumentListener getDocumentListener() { return new DocumentListener() { private volatile boolean ignore = false; @Override/*w ww . j a v a 2 s. c o m*/ public void insertUpdate(DocumentEvent e) { try { final String string = e.getDocument().getText(0, e.getDocument().getLength()).trim(); handle(string); } catch (BadLocationException ex) { log.error(null, ex); } } @Override public void removeUpdate(DocumentEvent e) { try { final String string = e.getDocument().getText(0, e.getDocument().getLength()).trim(); handle(string); } catch (BadLocationException ex) { log.error(null, ex); } } @Override public void changedUpdate(DocumentEvent e) { try { final String string = e.getDocument().getText(0, e.getDocument().getLength()).trim(); handle(string); } catch (BadLocationException ex) { log.error(null, ex); } } private void _handle(final String string) { // We are no longer busy. busySubject.notify(AutoCompleteJComboBox.this, false); if (AutoCompleteJComboBox.this.getSelectedItem() != null) { // Remember to use toString(). As getSelectedItem() can be // either StockInfo, or ResultSet. if (AutoCompleteJComboBox.this.getSelectedItem().toString().equals(string)) { // We need to differentiate, whether "string" is from user // typing, or drop down list selection. This is because when // user perform selection, document change event will be triggered // too. When string is from drop down list selection, user // are not expecting any auto complete suggestion. Return early. return; } } if (string.isEmpty()) { // Empty string. Return early. Do not perform hidePopup and // removeAllItems right here. As when user performs list // selection, previous text field item will be removed, and // cause us fall into this scope. We do not want to hidePopup // and removeAllItems when user is selecting his item. // // hidePopup and removeAllItems when user clears off all items // in text field, will be performed through keyReleased. return; } // Use to avoid endless DocumentEvent triggering. ignore = true; // During _handle operation, there will be a lot of ListDataListeners // trying to modify the content of our text field. We will not allow // them to do so. // // Without setReadOnly(true), when we type the first character "w", IME // will suggest ... However, when we call removeAllItems and addItem, // JComboBox will "commit" this suggestion to JComboBox's text field. // Hence, if we continue to type second character "m", the string displayed // at JComboBox's text field will be ... // AutoCompleteJComboBox.this.jComboBoxEditor.setReadOnly(true); // Must hide popup. If not, the pop up windows will not be // resized. AutoCompleteJComboBox.this.hidePopup(); AutoCompleteJComboBox.this.removeAllItems(); boolean shouldShowPopup = false; if (AutoCompleteJComboBox.this.stockInfoDatabase != null) { java.util.List<StockInfo> stockInfos = greedyEnabled ? stockInfoDatabase.greedySearchStockInfos(string) : stockInfoDatabase.searchStockInfos(string); sortStockInfosIfPossible(stockInfos); if (stockInfos.isEmpty() == false) { // Change to offline mode before adding any item. changeMode(Mode.Offline); } for (StockInfo stockInfo : stockInfos) { AutoCompleteJComboBox.this.addItem(stockInfo); shouldShowPopup = true; } if (shouldShowPopup) { AutoCompleteJComboBox.this.showPopup(); } else { } // if (shouldShowPopup) } // if (AutoCompleteJComboBox.this.stockInfoDatabase != null) if (shouldShowPopup == false) { // OK. We found nothing from offline database. Let's // ask help from online database. // We are busy contacting server right now. // TODO // Only enable ajaxYahooSearchEngineMonitor, till we solve // http://sourceforge.net/apps/mediawiki/jstock/index.php?title=TechnicalDisability busySubject.notify(AutoCompleteJComboBox.this, true); canRemoveAllItems = true; ajaxYahooSearchEngineMonitor.clearAndPut(string); ajaxGoogleSearchEngineMonitor.clearAndPut(string); } // When we are in windows look n feel, the text will always be selected. We do not want that. final Component component = AutoCompleteJComboBox.this.getEditor().getEditorComponent(); if (component instanceof JTextField) { JTextField jTextField = (JTextField) component; jTextField.setSelectionStart(jTextField.getText().length()); jTextField.setSelectionEnd(jTextField.getText().length()); jTextField.setCaretPosition(jTextField.getText().length()); } // Restore. AutoCompleteJComboBox.this.jComboBoxEditor.setReadOnly(false); ignore = false; } private void handle(final String string) { if (ignore) { return; } // Submit to GUI event queue. Used to avoid // Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification SwingUtilities.invokeLater(new Runnable() { @Override public void run() { _handle(string); } }); } }; }