/** * Накат истории вперед * * @param target Запись истории * @param textPane Текст для которого применяется историческое изменение */ public static void applyForward(UndoTextAction target, JTextComponent textPane) { if (target == null) throw new IllegalArgumentException("target==null"); if (textPane == null) throw new IllegalArgumentException("textPane==null"); try { javax.swing.text.Document doc = textPane.getDocument(); int offset = target.getOffset(); String changes = target.getChangedText(); if (UndoTextAction.Action.Added.equals(target.getAction())) { doc.insertString(offset, changes, null); int L = doc.getLength(); int P = offset + changes.length(); if (P > L) P = L; textPane.setCaretPosition(P); } else if (UndoTextAction.Action.Deleted.equals(target.getAction())) { doc.remove(offset, changes.length()); textPane.setCaretPosition(offset); } } catch (BadLocationException ex) { Logger.getLogger(UndoTextAction.class.getName()).log(Level.SEVERE, null, ex); } }
@Override public void focusGained(final FocusEvent e) { final JTextComponent component = getComponent(); if (!component.isEnabled() || !component.isEditable()) { super.focusGained(e); return; } mFocused = true; if (!shouldSelectAllOnFocus) { shouldSelectAllOnFocus = true; super.focusGained(e); return; } if (isMultiLineEditor) { super.focusGained(e); return; } final int end = component.getDocument().getLength(); final int dot = getDot(); final int mark = getMark(); if (dot == mark) { if (dot == 0) { component.setCaretPosition(end); component.moveCaretPosition(0); } else if (dot == end) { component.setCaretPosition(0); component.moveCaretPosition(end); } } super.focusGained(e); }
/** * 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()); } } }
protected void redispatchKeyEvents(final JTextComponent textComponent, KeyEvent firstKeyEvent) { if (textComponent.hasFocus()) { return; } final KeyboardFocusManager currentKeyboardFocusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); class KeyEventQueue implements KeyEventDispatcher, FocusListener { LinkedList events = new LinkedList(); public boolean dispatchKeyEvent(KeyEvent e) { events.add(e); return true; } public void focusGained(FocusEvent e) { e.getComponent().removeFocusListener(this); currentKeyboardFocusManager.removeKeyEventDispatcher(this); final Iterator iterator = events.iterator(); while (iterator.hasNext()) { final KeyEvent ke = (KeyEvent) iterator.next(); ke.setSource(textComponent); textComponent.dispatchEvent(ke); } } public void focusLost(FocusEvent e) {} }; final KeyEventQueue keyEventDispatcher = new KeyEventQueue(); currentKeyboardFocusManager.addKeyEventDispatcher(keyEventDispatcher); textComponent.addFocusListener(keyEventDispatcher); if (firstKeyEvent == null) { return; } if (firstKeyEvent.getKeyChar() == KeyEvent.CHAR_UNDEFINED) { switch (firstKeyEvent.getKeyCode()) { case KeyEvent.VK_HOME: textComponent.setCaretPosition(0); break; case KeyEvent.VK_END: textComponent.setCaretPosition(textComponent.getDocument().getLength()); break; } } else { textComponent.selectAll(); // to enable overwrite // redispath all key events textComponent.dispatchEvent(firstKeyEvent); } }
/** * Caret Listener * * @param e event */ public void caretUpdate(CaretEvent e) { log.finest("Dot=" + e.getDot() + ",Last=" + m_lastDot + ", Mark=" + e.getMark()); // Selection if (e.getDot() != e.getMark()) { m_lastDot = e.getDot(); return; } // // Is the current position a fixed character? if (e.getDot() + 1 > m_mask.length() || m_mask.charAt(e.getDot()) != DELIMITER) { m_lastDot = e.getDot(); return; } // Direction? int newDot = -1; if (m_lastDot > e.getDot()) // <- newDot = e.getDot() - 1; else // -> (or same) newDot = e.getDot() + 1; if (e.getDot() == 0) // first newDot = 1; else if (e.getDot() == m_mask.length() - 1) // last newDot = e.getDot() - 1; // log.fine( "OnFixedChar=" + m_mask.charAt(e.getDot()) + ", newDot=" + newDot + ", last=" + m_lastDot); // m_lastDot = e.getDot(); if (newDot >= 0 && newDot < getText().length()) m_tc.setCaretPosition(newDot); } // caretUpdate
/** * ************************************************************************ Delete String * * @param origOffset Offeset * @param length length * @throws BadLocationException */ @Override public void remove(int origOffset, int length) throws BadLocationException { log.finest("Offset=" + origOffset + " Length=" + length); if (origOffset < 0 || length < 0) throw new IllegalArgumentException("MDocNumber.remove - invalid argument"); int offset = origOffset; if (length != 1) { super.remove(offset, length); return; } /** Manual Entry */ String content = getText(); // remove all Thousands if (content.indexOf(m_groupingSeparator) != -1) { StringBuffer result = new StringBuffer(); for (int i = 0; i < content.length(); i++) { if (content.charAt(i) == m_groupingSeparator && i != origOffset) { if (i < offset) offset--; } else result.append(content.charAt(i)); } super.remove(0, content.length()); super.insertString(0, result.toString(), null); m_tc.setCaretPosition(offset); } // remove Thousands super.remove(offset, length); } // remove
/** Select or grow image when clicked. */ public void mousePressed(MouseEvent e) { Dimension size = fComponent.getSize(); if (e.getX() >= size.width - 7 && e.getY() >= size.height - 7 && getSelectionState() == 2) { // Click in selected grow-box: if (DEBUG) CampaignData.mwlog.infoLog("ImageView: grow!!! Size=" + fWidth + "x" + fHeight); Point loc = fComponent.getLocationOnScreen(); fGrowBase = new Point(loc.x + e.getX() - fWidth, loc.y + e.getY() - fHeight); // fGrowProportionally = e.isShiftDown(); } else { // Else select image: fGrowBase = null; JTextComponent comp = (JTextComponent) fContainer; int start = fElement.getStartOffset(); int end = fElement.getEndOffset(); int mark = comp.getCaret().getMark(); int dot = comp.getCaret().getDot(); if (e.isShiftDown()) { // extend selection if shift key down: if (mark <= start) comp.moveCaretPosition(end); else comp.moveCaretPosition(start); } else { // just select image, without shift: if (mark != start) comp.setCaretPosition(start); if (dot != end) comp.moveCaretPosition(end); } } }
public void keyPressed(KeyEvent event) { try { switch (event.getKeyCode()) { case KeyEvent.VK_ENTER: try { processInput.write(getLastLine(textComponent.getDocument()).getBytes()); processInput.flush(); } catch (IOException ioe) { Exceptions.printStackTrace(ioe); } break; case KeyEvent.VK_BACK_SPACE: Document doc = textComponent.getDocument(); if (!"\n".equals(getLastChar(doc))) { // NOI18N startOffset = doc.getLength() - 1; doc.remove(startOffset, 1); } break; } } catch (BadLocationException ex) { } // be sure caret position is adjusted in the case user move it from the end of doc textComponent.setCaretPosition(textComponent.getDocument().getLength()); startOffset = textComponent.getDocument().getLength(); }
/** * Delete String * * @param offset offset * @param length length * @throws BadLocationException */ @Override public void remove(int offset, int length) throws BadLocationException { log.finest("Offset=" + offset + ",Length=" + length); // begin of string if (offset == 0 || length == 0) { // empty the field // if the length is 0 or greater or equal with the mask length - teo_sarca, [ 1660595 ] Date // field: incorrect functionality on paste if (length >= m_mask.length() || length == 0) super.remove(offset, length); return; } // one position behind delimiter if (offset - 1 >= 0 && offset - 1 < m_mask.length() && m_mask.charAt(offset - 1) == DELIMITER) { if (offset - 2 >= 0) m_tc.setCaretPosition(offset - 2); else return; } else m_tc.setCaretPosition(offset - 1); } // deleteString
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) { } } }
private void setText(JTextComponent comp, String text) { if (text == null) { comp.setText(""); comp.setEnabled(false); comp.setEditable(false); } else { comp.setText(text); comp.setEnabled(true); comp.setEditable(true); } comp.setCaretPosition(0); }
private void updateCaretPosition(DocumentFilter.FilterBypass fb) throws BadLocationException { String allText = fb.getDocument().getText(0, fb.getDocument().getLength()); int index = allText.indexOf(':'); if (index != -1) { int minuteLength = allText.length() - index - 1; int hourLength = index; int caretPosition = tf.getCaretPosition(); if (minuteLength >= 2 && caretPosition == allText.length()) { tf.setCaretPosition(0); } else if (hourLength == caretPosition) { if (hourLength >= 2) { tf.setCaretPosition(3); } else if (hourLength == 1) { char c = allText.charAt(0); if (c != '0' && c != '1' && c != '2') { tf.setCaretPosition(2); } } } else if (hourLength + 1 == caretPosition) { if (hourLength == 1) { char c = allText.charAt(0); if (c == '0' || c == '1' || c == '2') { tf.setCaretPosition(caretPosition - 1); } } else if (hourLength == 0) { tf.setCaretPosition(caretPosition - 1); } } } if (allText.length() == 1) { tf.setCaretPosition(0); } }
/** * @param baseURL may be <code>null</code> * @see PropertyPanel.PropertyField#setText */ void setText(String text, String baseURL, DocumentListener documentListener) { // textComponent.getDocument().removeDocumentListener(documentListener); // if (editorType == EDITOR_TYPE_STYLED) { // // --- set content type --- ((JEditorPane) textComponent).setContentType("text/html"); // // --- set base URL --- try { // Note: baseURL is null if no baseURL is set for the corresponding property // Note: baseURL is empty if corporate baseURL is used but not set if (baseURL != null && !baseURL.equals("")) { ((HTMLDocument) textComponent.getDocument()).setBase(new URL(baseURL)); } } catch (MalformedURLException mue) { System.out.println("*** TextEditorPanel.setText(): invalid base URL: " + mue); } // // --- set text --- try { if (text.length() <= 59) { // ### 59 <html><head></head><body></body></html> + whitespace text = "<html><body><p></p></body></html>"; } textComponent.setText(text); textComponent.setCaretPosition(0); } catch (Throwable e) { textComponent.setText( "<html><body><font color=#FF0000>Page can't be displayed</font></body></html>"); System.out.println("*** TextEditorPanel.setText(): error while HTML rendering: " + e); } } else { textComponent.setText(text); textComponent.setCaretPosition(0); } // textComponent.getDocument().addDocumentListener(documentListener); }
/** * Log a message given the {@link AttributeSet}. * * @param line line * @param attributes attribute set, or null for none */ public void log(String line, AttributeSet attributes) { if (colorEnabled) { if (line.startsWith("(!!)")) { attributes = highlightedAttributes; } } try { int offset = document.getLength(); document.insertString( offset, line, (attributes != null && colorEnabled) ? attributes : defaultAttributes); textComponent.setCaretPosition(document.getLength()); } catch (BadLocationException ble) { } catch (NullPointerException npe) { } }
@Override public void modelPropertyChange(PropertyChangeEvent evt) { // Object oldValue = evt.getOldValue(); Object newValue = evt.getNewValue(); String propName = evt.getPropertyName(); if (BookController.StrandProps.UPDATE.check(propName)) { EntityUtil.refresh(mainFrame, scene.getStrand()); setEndBgColor(scene.getStrand().getJColor()); repaint(); return; } if (BookController.SceneProps.UPDATE.check(propName)) { Scene newScene = (Scene) newValue; if (!newScene.getId().equals(scene.getId())) { // not this scene return; } scene = newScene; lbSceneNo.setText(scene.getChapterSceneNo(false)); lbSceneNo.setToolTipText(scene.getChapterSceneToolTip()); lbStatus.setIcon(scene.getStatusIcon()); taTitle.setText(scene.getTitle()); taTitle.setCaretPosition(0); tcText.setText(scene.getSummary()); tcText.setCaretPosition(0); if (scene.hasSceneTs()) { if (!DateUtil.isZeroTimeDate(scene.getSceneTs())) { DateFormat formatter = I18N.getDateTimeFormatter(); lbTime.setText(formatter.format(scene.getSceneTs())); } else { lbTime.setText(""); } } return; } if (BookController.ChronoViewProps.ZOOM.check(propName)) { setZoomedSize((Integer) newValue); refresh(); } }
private void moveCtrlRight(boolean select) { String text = _textPane.getText(); int pos = _textPane.getCaretPosition() + 1; if (pos > text.length()) { return; } for (; pos < text.length(); ++pos) { if (isToStopAt(text.charAt(pos), text.charAt(pos - 1))) { break; } } if (select) { _textPane.moveCaretPosition(pos); } else { _textPane.setCaretPosition(pos); } }
private void moveCtrlLeft(boolean select) { String text = _textPane.getText(); int pos = _textPane.getCaretPosition() - 1; if (pos < 0) { return; } for (; pos > 0; --pos) { if (isToStopAt(text.charAt(pos - 1), text.charAt(pos))) { break; } } if (select) { _textPane.moveCaretPosition(pos); } else { _textPane.setCaretPosition(pos); } }
private void startEditing() { JTextComponent textField = (JTextComponent) combo.getEditor().getEditorComponent(); combo.setEditable(true); textField.requestFocus(); String text = initialEditValue; if (initialEditValue == null) { text = ""; // will revert to last valid value if invalid } combo.setSelectedItem(text); int i = text.indexOf("${}"); if (i != -1) { textField.setCaretPosition(i + 2); } else { textField.selectAll(); } }
/** * Insert the given String into the text component. If the string contains the | vertical BAr * char, then it will not be inserted, and the cursor will be set to its location. If there are * TWO vertical bars, then the text between them will be selected If the toInsert String is * multiLine, then indentation of all following lines will be the same as the first line. TAB * characters will be replaced by the number of spaces in the document's TAB property. * * @throws javax.swing.text.BadLocationException */ public static void insertMagicString(JTextComponent target, int dot, String toInsert) throws BadLocationException { Document doc = target.getDocument(); String[] lines = toInsert.split("\n"); if (lines.length > 1) { // multi line strings will need to be indented String tabToSpaces = getTab(target); String currentLine = getLineAt(target, dot); String currentIndent = getIndent(currentLine); StringBuilder sb = new StringBuilder(toInsert.length()); boolean firstLine = true; for (String l : lines) { if (!firstLine) { sb.append(currentIndent); } firstLine = false; // replace tabs with spaces. sb.append(l.replace("\t", tabToSpaces)); sb.append("\n"); } toInsert = sb.toString(); } if (toInsert.indexOf('|') >= 0) { int ofst = toInsert.indexOf('|'); int ofst2 = toInsert.indexOf('|', ofst + 1); toInsert = toInsert.replace("|", ""); doc.insertString(dot, toInsert, null); dot = target.getCaretPosition(); int strLength = toInsert.length(); if (ofst2 > 0) { // note that we already removed the first |, so end offset is now // one less than what it was. target.select(dot + ofst - strLength, dot + ofst2 - strLength - 1); } else { target.setCaretPosition(dot + ofst - strLength); } } else { doc.insertString(dot, toInsert, null); } }
/** * Sets the caret position of the given target to the given line and column * * @param line the first being 1 * @param column the first being 1 */ public static void setCaretPosition(JTextComponent target, int line, int column) { int p = getDocumentPosition(target, line, column); target.setCaretPosition(p); }
@Override public void refresh() { MigLayout layout = new MigLayout("fill,flowy,insets 4", "[]", "[][grow]"); setLayout(layout); setPreferredSize(new Dimension(size, size)); setComponentPopupMenu(EntityUtil.createPopupMenu(mainFrame, scene)); removeAll(); // set dotted border for scenes of other parts setBorder(SwingUtil.getBorderDefault()); if (scene.hasChapter()) { if (!scene.getChapter().getPart().getId().equals(mainFrame.getCurrentPart().getId())) { setBorder(SwingUtil.getBorderDot()); } } // button new btNew = getNewButton(); btNew.setSize20x20(); // btNew.setName(COMP_NAME_BT_NEW); // button remove btDelete = getDeleteButton(); btDelete.setSize20x20(); // btDelete.setName(COMP_NAME_BT_REMOVE); // button edit btEdit = getEditButton(); btEdit.setSize20x20(); // btEdit.setName(COMP_NAME_BT_EDIT); // chapter and scene number lbSceneNo = new JLabel("", SwingConstants.CENTER); lbSceneNo.setText(scene.getChapterSceneNo(false)); lbSceneNo.setToolTipText(scene.getChapterSceneToolTip()); lbSceneNo.setOpaque(true); lbSceneNo.setBackground(Color.white); // status lbStatus = new SceneStateLabel(scene.getSceneState(), true); // informational lbInformational = new JLabel(""); if (scene.getInformative()) { lbInformational.setIcon(I18N.getIcon("icon.small.info")); lbInformational.setToolTipText(I18N.getMsg("msg.common.informative")); } // scene time lbTime = addSceneTimeTextToPanel(); // title JScrollPane spTitle = generateTitlePane(); spTitle.setPreferredSize(new Dimension(50, 35)); // text JScrollPane spText = generateTextPane(); spText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); spText.setPreferredSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); // layout // button panel upperPanel = setupUpperPanel(); // main panel add(upperPanel, "growx"); add(spTitle, "growx, h 35!"); add(spText, "grow"); revalidate(); repaint(); tcText.setCaretPosition(0); taTitle.setCaretPosition(0); }
/** * Insert String * * @param offset offset * @param string string * @param attr attributes * @throws BadLocationException */ @Override public void insertString(int offset, String string, AttributeSet attr) throws BadLocationException { log.finest( "Offset=" + offset + ",String=" + string + ",Attr=" + attr + ",OldText=" + getText() + ",OldLength=" + getText().length()); // manual entry // DBTextDataBinder.updateText sends stuff at once - length=8 if (string != null && string.length() == 1) { // ignore if too long if (offset >= m_mask.length()) return; // is it an empty field? int length = getText().length(); if (offset == 0 && length == 0) { Date today = new Date(System.currentTimeMillis()); String dateStr = m_format.format(today); super.insertString(0, string + dateStr.substring(1), attr); m_tc.setCaretPosition(1); return; } // is it a digit ? try { Integer.parseInt(string); } catch (Exception pe) { // hengsin, [ 1660175 ] Date field - anoying popup // startDateDialog(); ADialog.beep(); return; } // try to get date in field, if invalid, get today's /*try { char[] cc = getText().toCharArray(); cc[offset] = string.charAt(0); m_format.parse(new String(cc)); } catch (ParseException pe) { startDateDialog(); return; }*/ // positioned before the delimiter - jump over delimiter if (offset != m_mask.length() - 1 && m_mask.charAt(offset + 1) == DELIMITER) m_tc.setCaretPosition(offset + 2); // positioned at the delimiter if (m_mask.charAt(offset) == DELIMITER) { offset++; m_tc.setCaretPosition(offset + 1); } super.remove(offset, 1); // replace current position } // Set new character super.insertString(offset, string, attr); // New value set Cursor if (offset == 0 && string != null && string.length() > 1) m_tc.setCaretPosition(0); } // insertString
public void removeUpdate(DocumentEvent e) { editor.setCaretPosition(e.getOffset()); }
private void highlightCompletedText(int start) { editor.setCaretPosition(getLength()); editor.moveCaretPosition(start); }
private void insertNewlineWithAutoIndent(JTextComponent text) { try { int caretPos = text.getCaretPosition(); StyledDocument doc = (StyledDocument) text.getDocument(); Element map = doc.getDefaultRootElement(); int lineNum = map.getElementIndex(caretPos); Element line = map.getElement(lineNum); int start = line.getStartOffset(); int end = line.getEndOffset() - 1; int len = end - start; String s = doc.getText(start, len); String leadingWS = PythonIndentation.getLeadingWhitespace(doc, start, caretPos - start); StringBuffer sb = new StringBuffer("\n"); sb.append(leadingWS); // TODO better control over automatic indentation indentationLogic.checkIndent(leadingWS, lineNum + 1); // If there is only whitespace between the caret and // the EOL, pressing Enter auto-indents the new line to // the same place as the previous line. int nonWhitespacePos = PythonIndentation.atEndOfLine(doc, caretPos, start, s, len); if (nonWhitespacePos == -1) { if (leadingWS.length() == len) { // If the line was nothing but whitespace, select it // so its contents get removed. text.setSelectionStart(start); } else { // Select the whitespace between the caret and the EOL // to remove it text.setSelectionStart(caretPos); } text.setSelectionEnd(end); text.replaceSelection(sb.toString()); // auto-indentation for python statements like if, while, for, try, // except, def, class and auto-deindentation for break, continue, // pass, return analyseDocument(doc, lineNum, indentationLogic); // auto-completion: add colon if it is obvious if (indentationLogic.shouldAddColon()) { doc.insertString(caretPos, ":", null); indentationLogic.setLastLineEndsWithColon(); } int lastLineChange = indentationLogic.shouldChangeLastLineIndentation(); int nextLineChange = indentationLogic.shouldChangeNextLineIndentation(); if (lastLineChange != 0) { Debug.log(5, "change line %d indentation by %d columns", lineNum + 1, lastLineChange); changeIndentation((DefaultStyledDocument) doc, lineNum, lastLineChange); // nextLineChange was determined based on indentation of last line before // the change nextLineChange += lastLineChange; } if (nextLineChange != 0) { Debug.log(5, "change line %d indentation by %d columns", lineNum + 2, nextLineChange); changeIndentation((DefaultStyledDocument) doc, lineNum + 1, nextLineChange); } } // If there is non-whitespace between the caret and the // EOL, pressing Enter takes that text to the next line // and auto-indents it to the same place as the last // line. Additional auto-indentation or dedentation for // specific python statements is only done for the next line. else { text.setCaretPosition(nonWhitespacePos); doc.insertString(nonWhitespacePos, sb.toString(), null); analyseDocument(doc, lineNum, indentationLogic); int nextLineChange = indentationLogic.shouldChangeNextLineIndentation(); if (nextLineChange != 0) { Debug.log(5, "change line %d indentation by %d columns", lineNum + 2, nextLineChange); changeIndentation((DefaultStyledDocument) doc, lineNum + 1, nextLineChange); } } } catch (BadLocationException ble) { text.replaceSelection("\n"); Debug.error(me + "Problem while inserting new line with auto-indent\n%s", ble.getMessage()); } }
@Override public void refresh() { MigLayout layout = new MigLayout("fill,flowy,insets 4", "[]", "[][grow]"); setLayout(layout); setPreferredSize(new Dimension(size, size)); setComponentPopupMenu(EntityUtil.createPopupMenu(mainFrame, scene)); removeAll(); // set dotted border for scenes of other parts setBorder(SwingUtil.getBorderDefault()); if (scene.hasChapter()) { if (!scene.getChapter().getPart().getId().equals(mainFrame.getCurrentPart().getId())) { setBorder(SwingUtil.getBorderDot()); } } // strand links StrandLinksPanel strandLinksPanel = new StrandLinksPanel(mainFrame, scene, true); // person links PersonLinksPanel personLinksPanel = new PersonLinksPanel(mainFrame, scene); // location links LocationLinksPanel locationLinksPanel = new LocationLinksPanel(mainFrame, scene); // location links ItemLinksPanel itemLinksPanel = new ItemLinksPanel(mainFrame, scene); // button new btNew = getNewButton(); btNew.setSize20x20(); // btNew.setName(COMP_NAME_BT_NEW); // button remove btDelete = getDeleteButton(); btDelete.setSize20x20(); // btDelete.setName(COMP_NAME_BT_REMOVE); // button edit btEdit = getEditButton(); btEdit.setSize20x20(); // btEdit.setName(COMP_NAME_BT_EDIT); // chapter and scene number lbSceneNo = new JLabel("", SwingConstants.CENTER); lbSceneNo.setText(scene.getChapterSceneNo(false)); lbSceneNo.setToolTipText(scene.getChapterSceneToolTip()); lbSceneNo.setOpaque(true); lbSceneNo.setBackground(Color.white); // status lbStatus = new SceneStateLabel(scene.getSceneState(), true); // informational lbInformational = new JLabel(""); if (scene.getInformative()) { lbInformational.setIcon(I18N.getIcon("icon.small.info")); lbInformational.setToolTipText(I18N.getMsg("msg.common.informative")); } // scene time lbTime = new JLabel(); if (scene.hasSceneTs()) { if (!DateUtil.isZeroTimeDate(scene.getSceneTs())) { lbTime.setText(DateUtil.simpleDateTimeToString(this.scene.getSceneTs())); } } // title taTitle = new UndoableTextArea(); taTitle.setName(CN_TITLE); taTitle.setText(scene.getTitle()); taTitle.setLineWrap(true); taTitle.setWrapStyleWord(true); taTitle.setDragEnabled(true); taTitle.setCaretPosition(0); taTitle.getUndoManager().discardAllEdits(); taTitle.addFocusListener(this); SwingUtil.addCtrlEnterAction(taTitle, new EditEntityAction(mainFrame, scene, true)); JScrollPane spTitle = new JScrollPane(taTitle); spTitle.setPreferredSize(new Dimension(50, 35)); // text tcText = SwingUtil.createTextComponent(mainFrame); tcText.setName(CN_TEXT); tcText.setText(scene.getText()); tcText.setDragEnabled(true); tcText.addFocusListener(this); SwingUtil.addCtrlEnterAction(tcText, new EditEntityAction(mainFrame, scene, true)); JScrollPane spText = new JScrollPane(tcText); spText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); spText.setPreferredSize(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE)); // layout // button panel JPanel buttonPanel = new JPanel(new MigLayout("flowy,insets 0")); buttonPanel.setName("buttonpanel"); buttonPanel.setOpaque(false); buttonPanel.add(btEdit); buttonPanel.add(btDelete); buttonPanel.add(btNew); upperPanel = new JPanel(new MigLayout("ins 0", "[][grow][]", "[top][top][top]")); upperPanel.setName(CN_UPPER_PANEL); upperPanel.setOpaque(false); upperPanel.add(lbSceneNo, "grow,width pref+10px,split 3"); upperPanel.add(lbStatus); upperPanel.add(lbInformational); upperPanel.add(strandLinksPanel, "grow"); upperPanel.add(buttonPanel, "spany 4,wrap"); JScrollPane scroller = new JScrollPane( personLinksPanel, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); scroller.setMinimumSize(new Dimension(20, 16)); scroller.setOpaque(false); scroller.getViewport().setOpaque(false); scroller.setBorder(null); upperPanel.add(scroller, "spanx 2,growx,wrap"); upperPanel.add(locationLinksPanel, "spanx 2,grow,wrap"); upperPanel.add(lbTime); // main panel add(upperPanel, "growx"); add(spTitle, "growx, h 35!"); add(spText, "grow"); revalidate(); repaint(); tcText.setCaretPosition(0); taTitle.setCaretPosition(0); }
/** * ************************************************************************ Insert String * * @param origOffset * @param string * @param attr * @throws BadLocationException */ @Override public void insertString(int origOffset, String string, AttributeSet attr) throws BadLocationException { log.finest("Offset=" + origOffset + " String=" + string + " Length=" + string.length()); if (origOffset < 0 || string == null) throw new IllegalArgumentException("Invalid argument"); int offset = origOffset; int length = string.length(); // From DataBinder (assuming correct format) if (length != 1) { super.insertString(offset, string, attr); return; } /** Manual Entry */ String content = getText(); // remove all Thousands if (content.indexOf(m_groupingSeparator) != -1) { StringBuffer result = new StringBuffer(); for (int i = 0; i < content.length(); i++) { if (content.charAt(i) == m_groupingSeparator) { if (i < offset) offset--; } else result.append(content.charAt(i)); } super.remove(0, content.length()); super.insertString(0, result.toString(), attr); // m_tc.setCaretPosition(offset); // ADebug.trace(ADebug.l6_Database, "Clear Thousands (" + m_format.toPattern() + ")" + content // + " -> " + result.toString()); content = result.toString(); } // remove Thousands /** * ******************************************************************** Check Character entered */ char c = string.charAt(0); if (Character.isDigit(c)) // c >= '0' && c <= '9') { // ADebug.trace(ADebug.l6_Database, "Digit=" + c); super.insertString(offset, string, attr); return; } // Decimal - remove other decimals // Thousand - treat as Decimal else if (c == m_decimalSeparator || c == m_groupingSeparator || c == '.' || c == ',') { // log.info("Decimal=" + c + " (ds=" + m_decimalSeparator + "; gs=" + m_groupingSeparator + // ")"); // no decimals on integers if (m_displayType == DisplayType.Integer) return; int pos = content.indexOf(m_decimalSeparator); // put decimal in String decimal = String.valueOf(m_decimalSeparator); super.insertString(offset, decimal, attr); // remove other decimals if (pos != 0) { content = getText(); StringBuffer result = new StringBuffer(); int correction = 0; for (int i = 0; i < content.length(); i++) { if (content.charAt(i) == m_decimalSeparator) { if (i == offset) result.append(content.charAt(i)); else if (i < offset) correction++; } else result.append(content.charAt(i)); } super.remove(0, content.length()); super.insertString(0, result.toString(), attr); m_tc.setCaretPosition(offset - correction + 1); } // remove other decimals } // decimal or thousand // something else else if (VNumber.AUTO_POPUP || "=+-/*%".indexOf(c) > -1) { // Minus - put minus on start of string if (c == m_minusSign && offset == 0) { // no minus possible if (m_displayType == DisplayType.Integer) return; // add at start of string else super.insertString(0, "-", attr); } else { log.fine("Input=" + c + " (" + (int) c + ")"); if (c == m_percentSign && offset > 0) { // don't convert integers to percent. 1% = 0? if (m_displayType == DisplayType.Integer) return; // divide by 100 else { String value = getText(); BigDecimal percentValue = new BigDecimal(0.0); try { if (value != null && value.length() > 0) { Number number = m_format.parse(value); percentValue = new BigDecimal(number.toString()); percentValue = percentValue.divide( new BigDecimal(100.0), m_format.getMaximumFractionDigits(), BigDecimal.ROUND_HALF_UP); m_tc.setText(m_format.format(percentValue)); } } catch (ParseException pe) { log.info("InvalidEntry - " + pe.getMessage()); } } } else { String result = VNumber.startCalculator(m_tc, getText(), m_format, m_displayType, m_title, c); super.remove(0, content.length()); // insertString(0, result, attr); m_tc.setText(result); } } } else ADialog.beep(); } // insertString
private static void moveCaretToEndOfDocument(JTextComponent jTextComponent) { if (jTextComponent.isEditable()) { Document document = jTextComponent.getDocument(); jTextComponent.setCaretPosition(document.getEndPosition().getOffset() - 1); } }