public void actionPerformed(ActionEvent e) { Object source = e.getSource(); Application.debug(tfScript.getText()); if (source == btApply) { Construction cons = app.getKernel().getConstruction(); button = textField ? app.getKernel().textfield(null, linkedGeo) : new GeoButton(cons); button.setEuclidianVisible(true); button.setAbsoluteScreenLoc(x, y); button.setLabel(null); button.setClickScript(tfScript.getText(), true); // set caption text String strCaption = tfCaption.getText().trim(); if (strCaption.length() > 0) { button.setCaption(strCaption); } button.setEuclidianVisible(true); button.setLabelVisible(true); button.updateRepaint(); geoResult = button; setVisible(false); app.getKernel().storeUndoInfo(); } else if (source == btCancel) { geoResult = null; setVisible(false); } }
private void outdentText(JTextComponent textComponent) throws BadLocationException { int tabSize = ((Integer) textComponent.getDocument().getProperty(PlainDocument.tabSizeAttribute)) .intValue(); String selectedText = textComponent.getSelectedText(); int newLineIndex = selectedText != null ? selectedText.indexOf('\n') : -1; if (newLineIndex >= 0) { int originalSelectionStart = textComponent.getSelectionStart(); int selectionStart = originalSelectionStart; int selectionEnd = textComponent.getSelectionEnd(); int lastNewLineBeforeSelection = textComponent.getText(0, selectionStart).lastIndexOf('\n'); int begin = lastNewLineBeforeSelection >= 0 ? lastNewLineBeforeSelection : 0; int end = selectionEnd; String text = textComponent.getText(begin, end - begin); if (lastNewLineBeforeSelection < 0) { text = "\n" + text; } int len = text.length(); StringBuffer out = new StringBuffer(len); for (int i = 0; i < len; i++) { char ch = text.charAt(i); out.append(ch); if (ch == '\n' && i < len - 1) { char next = text.charAt(i + 1); int stripCount = 0; if (next == '\t') { stripCount = 1; } else { for (; stripCount < tabSize && i + 1 + stripCount < len; stripCount++) { next = text.charAt(i + 1 + stripCount); if (next != ' ' && next != '\t') { break; } } } selectionEnd -= stripCount; if (i + begin < originalSelectionStart - 1) { selectionStart -= stripCount; } i += stripCount; } } textComponent.select(begin, end); textComponent.replaceSelection( lastNewLineBeforeSelection < 0 ? out.toString().substring(1) : out.toString()); textComponent.select(selectionStart, selectionEnd); } }
/** * This applies quick fixes which require insertion in the editor panel. * * @param markThisPart */ void insertSentenceStub( IvanErrorInstance myerror, List<String> stubs, String defaultStub, String markThisPart) { String[] unlocatedNames = myerror.Reference; /* Create location sentences. * 1. find the insertion point. The insertion point is somewhere to the right of the last cue. * 2. set the caret to the insertion point * 3. for each Name without location, insert a sentence. (unlocatedNames) * a) build a sentence: Name + Stub. Then insert it. * b) if you run out of stubs, create Name + " is on the … side." and then select the three dots. **/ // focus is important, so the user can readily start typing after clicking txtEditor.requestFocusInWindow(); // get insertion point int insertionpoint = findInsertionPoint(myerror.Codepoints); // set the caret txtEditor.setCaretPosition(insertionpoint); String sentence; if (stubs.size() > 0) { // build a sentence from a stub sentence = "\n" + unlocatedNames[0] + stubs.get(0) + " "; stubs.remove(0); // finalise last sentence with a period, if not present try { String text = txtEditor.getText(insertionpoint - 1, 1); if (!text.equals(".")) { sentence = "." + sentence; } } catch (BadLocationException e1) { e1.printStackTrace(); } // insert the sentence txtEditor.replaceSelection(sentence); } else { sentence = "\n" + unlocatedNames[0] + defaultStub; // finalise last sentence with a period, if not present try { String text = txtEditor.getText(insertionpoint - 1, 1); if (!text.equals(".")) { sentence = "." + sentence; } } catch (BadLocationException e1) { e1.printStackTrace(); } // insert the sentence txtEditor.replaceSelection(sentence); // select the … int dotspoint = txtEditor.getText().indexOf(markThisPart, insertionpoint); if (dotspoint > 0) { txtEditor.setCaretPosition(dotspoint); txtEditor.moveCaretPosition(dotspoint + markThisPart.length()); } } }
@Override public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { Rectangle r0 = null, r1 = null; try { r0 = c.modelToView(p0); r1 = c.modelToView(p1); } catch (BadLocationException ex) { // Nothing } if (r0 != null && r1 != null) { if (c instanceof JTextField) { g.setColor(color); g.fillRect(r0.x, r0.y, r1.x - r0.x, r0.height); g.setColor(Color.black); g.drawString(c.getText().substring(p0, p1), r0.x, r0.y + r0.height - 2); } else if (c instanceof JTextArea) { String str = c.getText().substring(p0, p1); int strMeasure = g.getFontMetrics().stringWidth(str); if (r0.x + strMeasure > c.getWidth() - 12) { int posX = r0.x, posY = r0.y + r0.height - 3; double countLine = 1; for (char ch : str.toCharArray()) { int chMeasure = g.getFontMetrics().charWidth(ch); if (posX + chMeasure > c.getWidth() - 12) { Double d1 = new Double(posX + ""); Double d2 = new Double(strMeasure + ""); Double d3 = new Double(c.getWidth() + ""); if ((d1 + d2) / d3 > countLine) { posX = 6; posY += r0.height; countLine += 1.0d; } } g.setColor(color); g.fillRect(posX, posY - r0.height - 3, chMeasure, r0.height); g.setColor(Color.black); g.drawString(ch + "", posX, posY); posX += chMeasure; } } else { int RX = r1.x - r0.x < 0 ? strMeasure : r1.x - r0.x; g.setColor(color); g.fillRect(r0.x, r0.y, RX, r0.height); g.setColor(Color.black); g.drawString(str, r0.x, r0.y + r0.height - 3); } } } }
/** See if edit value is valid, put error message in buff. */ protected boolean _validate(StringBuffer buff) { String editValue = tf.getText().trim(); if (editValue.length() == 0) return true; // empty ok try { new TimeDuration(tf.getText()); return true; } catch (java.text.ParseException e) { buff.append(label).append(": ").append(e.getMessage()); return false; } }
@Override public void focusLost(FocusEvent e) { if (e.getSource() instanceof JTextComponent) { JTextComponent tc = (JTextComponent) e.getSource(); switch (tc.getName()) { case CN_TITLE: scene.setTitle(tc.getText()); break; case CN_TEXT: scene.setSummary(tc.getText()); break; } mainFrame.getBookController().updateScene(scene); } }
public static List<String> validateWidget(Object[] o) { List msg = new ArrayList(); if (o.length > 0) { for (Object s : o) { JTextComponent f = (JTextComponent) s; if (StringUtil.isEmptyString(f.getText().trim())) { msg.add(f.getToolTipText()); } if ((f.getClass() != JFormattedTextField.class) || (!StringUtil.isEqualString("- -", f.getText().trim()))) continue; msg.add(f.getToolTipText()); } } return msg; }
@Override public void searchResultsUpdated(SearchResults sr) { if (mySearchTextComponent.getText().isEmpty()) { updateUIWithEmptyResults(); } else { int count = sr.getMatchesCount(); boolean notTooMuch = count <= mySearchResults.getMatchesLimit(); myMatchInfoLabel.setText( notTooMuch ? ApplicationBundle.message("editorsearch.matches", count) : ApplicationBundle.message( "editorsearch.toomuch", mySearchResults.getMatchesLimit())); myClickToHighlightLabel.setVisible(!notTooMuch); if (notTooMuch) { if (count > 0) { setRegularBackground(); } else { setNotFoundBackground(); } } else { setRegularBackground(); } } myReplaceActionsToolbar1.updateActionsImmediately(); }
/** Retrieves the value from the specified text field as a {@link String}. */ @SuppressWarnings({"UnusedCatchParameter"}) private String getTextComponentValueAsString(final JTextComponent textComponent) { if (SwingUtilities.isEventDispatchThread()) { final String textFieldValue; try { final String text1 = textComponent.getText(); textFieldValue = (text1 != null) ? text1.trim() : null; } catch (Exception e) { LOG.error("Exception while getting the value from text field. Returning null instead.", e); return null; } return textFieldValue; } else { final String[] textFieldValue = new String[1]; try { SwingUtilities.invokeAndWait( new Runnable() { public void run() { textFieldValue[0] = textComponent.getText(); } }); } catch (Exception e) { LOG.error("Exception while getting the value from text field. Returning null instead.", e); return null; } return textFieldValue[0]; } }
public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); // as a coding convenience, create a reference to the text component // that is typecast to JTextComponent. this is not essential, as we // could typecast every reference, but this makes the code cleaner JTextComponent _theComponent = (JTextComponent) DataTypeTime.this._textComponent; String text = _theComponent.getText(); // tabs and newlines get put into the text before this check, // so remove them // This only applies to Popup editing since these chars are // not passed to this level by the in-cell editor. if (c == KeyEvent.VK_TAB || c == KeyEvent.VK_ENTER) { // remove all instances of the offending char int index = text.indexOf(c); if (index == text.length() - 1) { text = text.substring(0, text.length() - 1); // truncate string } else { text = text.substring(0, index) + text.substring(index + 1); } ((IRestorableTextComponent) _theComponent).updateText(text); _beepHelper.beep(_theComponent); e.consume(); } // handle cases of null // The processing is different when nulls are allowed and when they are not. // if (DataTypeTime.this._isNullable) { // user enters something when field is null if (text.equals("<null>")) { if ((c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) { // delete when null => original value DataTypeTime.this._textComponent.restoreText(); e.consume(); } else { // non-delete when null => clear field and add text DataTypeTime.this._textComponent.updateText(""); // fall through to normal processing of this key stroke } } else { // check for user deletes last thing in field if ((c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) { if (text.length() <= 1) { // about to delete last thing in field, so replace with null DataTypeTime.this._textComponent.updateText("<null>"); e.consume(); } } } } else { // field is not nullable // handleNotNullableField(text, c, e, _textComponent); } }
private void replaceFieldDocumentChanged() { setMatchesLimit(LivePreviewController.MATCHES_LIMIT); myFindModel.setStringToReplace(myReplaceTextComponent.getText()); if (myReplaceTextComponent instanceof JTextArea) { adjustRows((JTextArea) myReplaceTextComponent); } updateMultiLineStateIfNeed(); }
private void promptForTime() { JTextComponent field = (JTextComponent) editor; String prompt = field.getText(); prompt = prompt + "(???)"; field.setText(prompt); int len = prompt.length(); field.select(len - 4, len - 1); }
private String readInt(JTextComponent textComponent) throws IncorrectInputException { String text = textComponent.getText(); if (Character.isDigit(text.charAt(0))) { return text; } else { throw new IncorrectInputException("wrong input"); } }
// get current value from editComponent protected Object getEditValue() { String editValue = tf.getText().trim(); if (editValue.length() == 0) return null; // empty ok try { return new TimeDuration(editValue); } catch (java.text.ParseException e) { return null; } }
@Override @Nullable public Object getData(@NonNls final String dataId) { if (SpeedSearchSupply.SPEED_SEARCH_CURRENT_QUERY.is(dataId)) { return mySearchTextComponent.getText(); } if (CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.is(dataId)) { return myEditor; } return null; }
private void addString(final String str) { final Document doc = target.getDocument(); if (doc != null) { try { // Application.instance.getMainFrame().updateContentPanel(true); doc.insertString(doc.getLength(), str, null); target.setCaretPosition(target.getText().length()); } catch (final BadLocationException e) { } } }
@SuppressWarnings("unchecked") @Test public void testNonNullFromPropertyWithoutInitialText() throws BadLocationException { JTextComponent component = new JTextField(); ReadableWritableProperty<String, String> property = new JTextComponentTextProperty(component); ValueChangeListener<String> listenerMock = (ValueChangeListener<String>) mock(ValueChangeListener.class); property.addValueChangeListener(listenerMock); assertEquals("", component.getDocument().getText(0, component.getDocument().getLength())); assertEquals("", component.getText()); assertEquals("", property.getValue()); property.setValue("new text"); assertEquals("new text", component.getText()); // Check exactly one event fired verify(listenerMock).valueChanged(property, "", "new text"); verify(listenerMock) .valueChanged(any(JTextComponentTextProperty.class), anyString(), anyString()); }
public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE || e.getKeyCode() == KeyEvent.VK_ENTER) { String text = textEditor.getText(); if (comboBox.isShowing()) { suggestionList.hide(); suggestionList.filter(text); suggestionList.show(); } } }
public void testInsertTextChecksThatTheComponentIsEditable() throws Exception { textBox.setText("text"); jTextComponent.setEditable(false); try { textBox.insertText("new text", 0); throw new AssertionFailureNotDetectedError(); } catch (AssertionFailedError e) { assertEquals("The text box is not editable", e.getMessage()); } assertEquals("text", jTextComponent.getText()); }
private void indentText(JTextComponent textComponent) throws BadLocationException { String selectedText = textComponent.getSelectedText(); int newLineIndex = selectedText != null ? selectedText.indexOf('\n') : -1; if (newLineIndex >= 0) { int originalSelectionStart = textComponent.getSelectionStart(); int selectionStart = originalSelectionStart; int selectionEnd = textComponent.getSelectionEnd(); int lastNewLineBeforeSelection = textComponent.getText(0, selectionStart).lastIndexOf('\n'); int begin = lastNewLineBeforeSelection >= 0 ? lastNewLineBeforeSelection : 0; int end = selectionEnd; String text = textComponent.getText(begin, end - begin); int len = text.length(); StringBuffer out = new StringBuffer(len); if (lastNewLineBeforeSelection < 0) { out.insert(0, '\t'); selectionStart++; selectionEnd++; } for (int i = 0; i < len; i++) { char ch = text.charAt(i); out.append(ch); if (ch == '\n' && i < len - 1) { out.append("\t"); selectionEnd++; if (begin + i < originalSelectionStart) { selectionStart++; } } } textComponent.select(begin, end); textComponent.replaceSelection(out.toString()); textComponent.select(selectionStart, selectionEnd); } else { textComponent.replaceSelection("\t"); } }
@Override public void updateUI() { super.updateUI(); String text = getParameter().getValueAsText(); JTextComponent textField = getTextComponent(); if (!textField.getText().equals(text)) { textField.setText(text); } if (textField.isEnabled() != isEnabled()) { textField.setEnabled(isEnabled()); } }
/** * 入力の制限されたテキストフィールドを返します. * * @return * @throws IllegalArgumentException {@link FileNameEditor#createTreeCellEditorForText() * }で作成されたセルエディタの{@link DefaultCellEditor#getComponent() }が{@link JTextComponent}でないとき */ @Override protected final TreeCellEditor createTreeCellEditor() { DefaultCellEditor cellEditor = createTreeCellEditorForText(); if (!(cellEditor.getComponent() instanceof JTextComponent)) { throw new IllegalStateException(); } JTextComponent editor = (JTextComponent) cellEditor.getComponent(); String value = editor.getText(); editor.setDocument(new FileNameDocument()); editor.setText(value); return cellEditor; }
private void updateReplaceComponent() { final int oldCaretPosition = myReplaceTextComponent != null ? myReplaceTextComponent.getCaretPosition() : 0; String oldText = myReplaceTextComponent != null ? myReplaceTextComponent.getText() : myFindModel.getStringToReplace(); if (!updateTextComponent(false)) { return; } if (oldText != null) { myReplaceTextComponent.setText(oldText); } myReplaceTextComponent .getDocument() .addDocumentListener( new DocumentAdapter() { @Override protected void textChanged(DocumentEvent e) { ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { replaceFieldDocumentChanged(); } }); } }); if (!getFindModel().isMultiline()) { new ReplaceOnEnterAction(this, myReplaceTextComponent); } // myReplaceTextComponent.setText(myFindModel.getStringToReplace()); ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { myReplaceTextComponent.setCaretPosition(oldCaretPosition); } }); new VariantsCompletionAction(myReplaceTextComponent); new NextOccurrenceAction(this, myReplaceFieldWrapper); new PrevOccurrenceAction(this, myReplaceFieldWrapper); myReplaceFieldWrapper.revalidate(); myReplaceFieldWrapper.repaint(); }
protected int getNextMatch( JTextComponent textComp, String str, int startingOffset, Position.Bias bias) { String text = textComp.getText(); if (ignoreCase) { str = str.toUpperCase(); text = text.toUpperCase(); } return bias == null || bias == Position.Bias.Forward ? text.indexOf(str, startingOffset) : text.lastIndexOf(str, startingOffset); }
@Override protected void paintSafely(Graphics g) { super.paintSafely(g); JTextComponent comp = getComponent(); if (hint != null && comp.getText().length() == 0 && (!(hideOnFocus && comp.hasFocus()))) { if (color != null) { g.setColor(color); } else { g.setColor(comp.getForeground().brighter().brighter().brighter()); } int padding = (comp.getHeight() - comp.getFont().getSize()) / 2; g.drawString(hint, 3, comp.getHeight() - padding - 1); } }
private void searchFieldDocumentChanged() { setMatchesLimit(LivePreviewController.MATCHES_LIMIT); String text = mySearchTextComponent.getText(); myFindModel.setStringToFind(text); if (!StringUtil.isEmpty(text)) { updateResults(true); } else { nothingToSearchFor(); } if (mySearchTextComponent instanceof JTextArea) { adjustRows((JTextArea) mySearchTextComponent); } updateMultiLineStateIfNeed(); }
private boolean isEmptyFields() { boolean state = false; javax.swing.text.JTextComponent textField; String date; for (int i = 0; i <= manageEdit.getPnFields().getComponentCount(); i++) { try { textField = (javax.swing.text.JTextComponent) manageEdit.getPnFields().getComponent(i); if (textField.getText().equals("")) { state = true; textField.requestFocus(); } else if (textField.getText().indexOf("-") != -1) { String special = textField.getText().trim(); if ((special.length() < 12) && (special.length() != 10)) { state = true; textField.requestFocus(); } } } catch (Exception e) { } } return state; }
/** * Highlight a string in a JifTextComponent * * @param component Instance of JifTextComponent * @param pattern String to be highlighted */ public void highlight(JTextComponent component, String pattern) { try { Highlighter hilite = component.getHighlighter(); String text = jif.getText(); int pos = 0; while ((pos = text.indexOf(pattern, pos)) >= 0) { hilite.addHighlight(pos, pos + pattern.length(), this); pos += pattern.length(); } } catch (BadLocationException e) { System.out.println(e.getMessage()); System.err.println(e.getMessage()); } }
public boolean verify(JComponent input) { JTextComponent jtc = (JTextComponent) input; if (!jtc.isEnabled()) return true; if (!jtc.isEditable()) return true; Number num = self.value; if (num != null) { try { checkRange(num); } catch (Exception ex) { input.putClientProperty("Verification-Error", ex.getMessage()); // tooltip.setText(ex.getMessage()); // tooltip.show(input); return false; } } else if (jtc.getText() != null && jtc.getText().length() > 0) { jtc.setText(""); } input.putClientProperty("Verification-Error", null); // tooltip.hide(); self.finalizeValue(); return true; }
public void run() { String text = textEditor.getText(); // need to hide first because Swing incorrectly updates popups (getSize() returns // dimension not the same as seen on the screen) suggestionList.hide(); if (comboBox.isShowing()) { suggestionList.filter(text); if (suggestionList.getItemCount() > 0) { suggestionList.show(); } } }