Java/Swing JFC/JTextComponent

Материал из Java эксперт
Версия от 06:45, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Better way to set the selection

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();
    c.select(10, 20);
  }
}





Creating a Custom Editing Command for a JTextComponent

  
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.TextAction;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea comp = new JTextArea();
    String actionName = "Lowercase";
    
    JFrame f = new JFrame();
    f.add(new JScrollPane(comp));
    f.setSize(300,300);
    f.setVisible(true);
    comp.getInputMap().put(KeyStroke.getKeyStroke("F2"), actionName);
    comp.getActionMap().put(actionName, new TextAction(actionName) {
      public void actionPerformed(ActionEvent evt) {
        JTextComponent comp = getTextComponent(evt);
        if (comp.getSelectionStart() == comp.getSelectionEnd()) {
          if (comp.getCaretPosition() < comp.getDocument().getLength()) {
            try {
              int pos = comp.getCaretPosition();
              Document doc = comp.getDocument();
              String str = doc.getText(pos, 1).toLowerCase();
              doc.remove(pos, 1);
              doc.insertString(pos, str, null);
              comp.moveCaretPosition(pos + 1);
            } catch (Exception e) {
              System.out.println();
            }
          }
        } else {
          int s = comp.getSelectionStart();
          int e = comp.getSelectionEnd();
          comp.replaceSelection(comp.getSelectedText().toLowerCase());
          comp.select(s, e);
        }
      }
    });
  }
}





Enabling Text-Dragging on a JTextComponent

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textComp = new JTextArea();
    textComp.setDragEnabled(true);
  }
}





Enumerating All the Views in a JTextComponent

  
import javax.swing.JTextPane;
import javax.swing.text.JTextComponent;
import javax.swing.text.View;
public class Main {
  public static void main(String[] argv) {
    JTextComponent textComp = new JTextPane();
    View v = textComp.getUI().getRootView(textComp);
    walkView(v, 0);
  }
  public static void walkView(View view, int level) {
    int n = view.getViewCount();
    for (int i = 0; i < n; i++) {
      walkView(view.getView(i), level + 1);
    }
  }
}





Filter all editing operations on a text component

  

import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent textComponent = new JTextField();
    AbstractDocument doc = (AbstractDocument) textComponent.getDocument();
    doc.setDocumentFilter(new FixedSizeFilter(10));
  }
}
class FixedSizeFilter extends DocumentFilter {
  int maxSize;
  public FixedSizeFilter(int limit) {
    maxSize = limit;
  }
  public void insertString(DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet attr)
      throws BadLocationException {
    replace(fb, offset, 0, str, attr);
  }
  public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String str,
      AttributeSet attrs) throws BadLocationException {
    int newLength = fb.getDocument().getLength() - length + str.length();
    if (newLength <= maxSize) {
      fb.replace(offset, length, str, attrs);
    } else {
      throw new BadLocationException("New characters exceeds max size of document", offset);
    }
  }
}





Get the first 3 characters

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent tc = new JTextArea("Initial Text");
    int docLength = tc.getDocument().getLength();
    // Get all text
    String text = tc.getText();
    // Get the first 3 characters
    int offset = 0;
    int len = 3;
    text = tc.getText(offset, len);
  }
}





Get the last 3 characters

  

import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent tc = new JTextArea("Initial Text");
    int docLength = tc.getDocument().getLength();
    String text = tc.getText();
    // Get the last 3 characters
    int offset = docLength - 3;
    int len = 3;
    text = tc.getText(offset, len);
  }
}





Get value from JTextCompnent and convert it to upper case

  
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class Main implements ActionListener {
  JTextField jtf = new JTextField(10);
  JButton jbtnGetTextUpper = new JButton("Get Text In Uppercase");
  Main() {
    JFrame jfrm = new JFrame("Demonstrate a Text Field");
    jfrm.setLayout(new FlowLayout());
    jfrm.setSize(240, 140);
    jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jtf.setActionCommand("TF");
    jtf.addActionListener(this);
    jbtnGetTextUpper.addActionListener(this);
    jtf.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent ce) {
        System.out.println("Text in real time: " + jtf.getText());
      }
    });
    jfrm.add(jtf);
    jfrm.add(jbtnGetTextUpper);
    jfrm.setVisible(true);
  }
  public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand().equals("TF")) {
      System.out.println("ENTER key pressed: " + jtf.getText());
    } else {
      String str = jtf.getText().toUpperCase();
      System.out.println("Button pressed: " + str);
    }
  }
  public static void main(String args[]) {
    new Main();
  }
}





Highlight a word in JTextComponent

  
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textComp = new JTextArea();
    Highlighter hilite = textComp.getHighlighter();
    Highlighter.Highlight[] hilites = hilite.getHighlights();
    for (int i = 0; i < hilites.length; i++) {
      if (hilites[i].getPainter() instanceof MyHighlightPainter) {
        hilite.removeHighlight(hilites[i]);
      }
    }
    highlight(textComp);
  }
  public static void highlight(JTextComponent textComp) {
    try {
      Highlighter hilite = textComp.getHighlighter();
      Document doc = textComp.getDocument();
      hilite.addHighlight(3, 5, new MyHighlightPainter(Color.red));
    } catch (BadLocationException e) {
      e.printStackTrace();
    }
  }
}
class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
  public MyHighlightPainter(Color color) {
    super(color);
  }
}





Limiting the Capacity of a JTextComponent

  
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
public class Main {
  public static void main(String[] argv) {
    JTextComponent textComp = new JTextField();
    textComp.setDocument(new FixedSizePlainDocument(10));
  }
}
class FixedSizePlainDocument extends PlainDocument {
  int maxSize;
  public FixedSizePlainDocument(int limit) {
    maxSize = limit;
  }
  public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
    if ((getLength() + str.length()) <= maxSize) {
      super.insertString(offs, str, a);
    } else {
      throw new BadLocationException("Insertion exceeds max size of document", offs);
    }
  }
}





Listening for Caret Movement Events in a JTextComponent

  
import javax.swing.JTextArea;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent textComp = new JTextArea();
    textComp.addCaretListener(new CaretListener() {
      public void caretUpdate(CaretEvent e) {
        int dot = e.getDot();
        System.out.println("dot is the caret position:" + dot);
        int mark = e.getMark();
        System.out.println("mark is the non-caret end of the selection: " + mark);
      }
    });
  }
}





Listening for Editing Changes in a JTextComponent

  
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textcomp = new JTextPane();
    textcomp.setText("Initial Text");
    textcomp.getDocument().addDocumentListener(new DocumentListener() {
      public void insertUpdate(DocumentEvent evt) {
        int off = evt.getOffset();
        System.out.println("off:"+off);
        int len = evt.getLength();
        System.out.println("len:"+len);
        try {
          String str = evt.getDocument().getText(off, len);
          System.out.println(str);
        } catch (BadLocationException e) {
        }
      }
      public void removeUpdate(DocumentEvent evt) {
        int off = evt.getOffset();
        System.out.println("off:"+off);
        int len = evt.getLength();
        System.out.println("len:"+len);
      }
      public void changedUpdate(DocumentEvent evt) {
        int off = evt.getOffset();
        System.out.println("off:"+off);
        int len = evt.getLength();
        System.out.println("len:"+len);
      }
    });
  }
}





Listing the Key Bindings in a JTextComponent Keymap

  
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.Action;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.Keymap;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea component = new JTextArea();
    Keymap map = component.getKeymap();
    while (map != null) {
      KeyStroke[] keys = map.getBoundKeyStrokes();
      for (int i = 0; i < keys.length; i++) {
        System.out.println(keys[i].getKeyChar());        
        Action action = (Action) map.getAction(keys[i]);
        System.out.println(action);
      }
      Action defAction = map.getDefaultAction();
      System.out.println(defAction);
      map = map.getResolveParent();
    }
  }
}





Modifying Text in a JTextComponent: Append some text

  

import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textComp = new JTextField("Initial Text");
    Document doc = textComp.getDocument();
    // Append some text
    doc.insertString(doc.getLength(), "some text", null);
  }
}





Modifying Text in a JTextComponent: Delete the first 5 characters

  
import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textComp = new JTextField("Initial Text");
    Document doc = textComp.getDocument();
    // Delete the first 5 characters
    int pos = 0;
    int len = 5;
    doc.remove(pos, len);
  }
}





Modifying Text in a JTextComponent: Insert some text after the 5th character

  
import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textComp = new JTextField("Initial Text");
    Document doc = textComp.getDocument();
    // Insert some text after the 5th character
    int pos = 5;
    doc.insertString(pos, "some text", null);
  }
}





Modifying Text in a JTextComponent: Insert some text at the beginning

  
import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textComp = new JTextField("Initial Text");
    Document doc = textComp.getDocument();
    // Insert some text at the beginning
    int pos = 0;
    doc.insertString(pos, "some text", null);
  }
}





Modifying Text in a JTextComponent: Replace the first 3 characters with some text

  

import javax.swing.JTextField;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent textComp = new JTextField("Initial Text");
    Document doc = textComp.getDocument();
    // Replace the first 3 characters with some text
    int pos = 0;
    int len = 3;
    doc.remove(pos, len);
    doc.insertString(pos, "new text", null);
  }
}





Moving the Caret of a JTextComponent

  
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextComponent c = new JTextArea();
    c.getCaretPosition();
    if (c.getCaretPosition() < c.getDocument().getLength()) {
      char ch = c.getText(c.getCaretPosition(), 1).charAt(0);
    }
    // Move the caret
    int newPosition = 0;
    c.moveCaretPosition(newPosition);
  }
}





Overriding a Few Default Typed Key Bindings in a JTextComponent

  
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField(10);
    // Override letter a
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("typed a"),"actionName");
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(new Character(" "), 0), "actionName");
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("typed X"), "none");
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("shift pressed SPACE"), "actionName");
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(new Character(" "), 0), "none");
    MyAction action  = new MyAction();
    
    component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("pressed SPACE"),action.getValue(Action.NAME));
    component.getActionMap().put(action.getValue(Action.NAME), action);
  }
}
class MyAction extends AbstractAction{
  public MyAction(){
    super("Insert Space");
  }
  public void actionPerformed(ActionEvent evt) {
    JTextComponent c = (JTextComponent) evt.getSource();
    try {
      c.getDocument().insertString(c.getCaretPosition(), " ", null);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Remove Highlighting in a JTextComponent

  
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textComp = new JTextArea();
    removeHighlights(textComp);
  }
  public static void removeHighlights(JTextComponent textComp) {
    Highlighter hilite = textComp.getHighlighter();
    Highlighter.Highlight[] hilites = hilite.getHighlights();
    for (int i = 0; i < hilites.length; i++) {
      if (hilites[i].getPainter() instanceof MyHighlightPainter) {
        hilite.removeHighlight(hilites[i]);
      }
    }
  }
}





Replace selected text

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();
    c.replaceSelection("replacement text");
  }
}





Set the color behind the selected text

  
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();
    c.setSelectionColor(Color.green);
  }
}





Set the color of text inside the selection

  
import java.awt.Color;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();
    c.setSelectedTextColor(Color.red);
  }
}





Setting the Blink Rate of a JTextComponent"s Caret

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();
    // Set rate to blink once a second
    c.getCaret().setBlinkRate(1000);
    // Set the caret to stop blinking
    c.getCaret().setBlinkRate(0);
  }
}





Sharing a Document Between JTextComponents

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent textComp1 = new JTextArea();
    JTextComponent textComp2 = new JTextArea();
    textComp2.setDocument(textComp1.getDocument());
  }
}





Using a Position in a JTextComponent

  
import javax.swing.JTextArea;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Position;
public class Main {
  public static void main(String[] argv) throws Exception{
    JTextComponent textComp = new JTextArea();
    Document doc = textComp.getDocument();
    Position p = null;
    int location = 3;
    p = doc.createPosition(location);
  }
}





Using the Selection of a JTextComponent

  
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class Main {
  public static void main(String[] argv) {
    JTextComponent c = new JTextArea();
    // Get text inside selection
    c.getSelectedText();
  }
}