Java Tutorial/Swing/JTextComponent

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

Содержание

Accessing the System Clipboard

import java.awt.BorderLayout;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.DefaultEditorKit;
public class CutPasteSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Cut/Paste Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    Action actions[] = textField.getActions();
    Action cutAction = findAction(actions, DefaultEditorKit.cutAction);
    Action copyAction = findAction(actions, DefaultEditorKit.copyAction);
    Action pasteAction = findAction(actions, DefaultEditorKit.pasteAction);
    JPanel panel = new JPanel();
    frame.add(panel, BorderLayout.SOUTH);
    JButton cutButton = new JButton(cutAction);
    cutButton.setText("Cut");
    panel.add(cutButton);
    JButton copyButton = new JButton(copyAction);
    copyButton.setText("Copy");
    panel.add(copyButton);
    JButton pasteButton = new JButton(pasteAction);
    pasteButton.setText("Paste");
    panel.add(pasteButton);
    frame.setSize(250, 250);
    frame.setVisible(true);
  }
  
  private static Action findAction(Action actions[], String key) {
    Hashtable<Object, Action> commands = new Hashtable<Object, Action>();
    for (int i = 0; i < actions.length; i++) {
      Action action = actions[i];
      commands.put(action.getValue(Action.NAME), action);
    }
    return commands.get(key);
  }
  
}





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);
  }
}





CaretListener Interface and CaretEvent Class

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class CaretSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Caret Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    frame.add(scrollPane, BorderLayout.CENTER);
    
    CaretListener listener = new CaretListener() {
      public void caretUpdate(CaretEvent caretEvent) {
        System.out.println("Dot: "+ caretEvent.getDot());
        System.out.println("Mark: "+caretEvent.getMark());
      }
    };
    textArea.addCaretListener(listener);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Default Editor Kit: cutAction

import java.awt.BorderLayout;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.DefaultEditorKit;
public class CutPasteSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Cut/Paste Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    Action actions[] = textField.getActions();
    Action cutAction = findAction(actions, DefaultEditorKit.cutAction);
    Action copyAction = findAction(actions, DefaultEditorKit.copyAction);
    Action pasteAction = findAction(actions, DefaultEditorKit.pasteAction);
    JPanel panel = new JPanel();
    frame.add(panel, BorderLayout.SOUTH);
    JButton cutButton = new JButton(cutAction);
    cutButton.setText("Cut");
    panel.add(cutButton);
    JButton copyButton = new JButton(copyAction);
    copyButton.setText("Copy");
    panel.add(copyButton);
    JButton pasteButton = new JButton(pasteAction);
    pasteButton.setText("Paste");
    panel.add(pasteButton);
    frame.setSize(250, 250);
    frame.setVisible(true);
  }
  
  private static Action findAction(Action actions[], String key) {
    Hashtable<Object, Action> commands = new Hashtable<Object, Action>();
    for (int i = 0; i < actions.length; i++) {
      Action action = actions[i];
      commands.put(action.getValue(Action.NAME), action);
    }
    return commands.get(key);
  }
  
}





Document and DocumentFilter

import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
public class MainClass {
  public static void main(String[] args) throws Exception {
    JTextField field = new JTextField(30);
    ((AbstractDocument) (field.getDocument())).setDocumentFilter(new DocumentFilter() {
      public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr)
          throws BadLocationException {
        System.out.println("insert");
        fb.insertString(offset, string.toUpperCase(), attr);
      }
      public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attr)
          throws BadLocationException {
        System.out.println("replace");
        fb.replace(offset, length, string.toUpperCase(), attr);
      }
    });
    JFrame frame = new JFrame("User Information");
    frame.getContentPane().add(field);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
  }
}





Drawing in the Background of a Component

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JTextAreaBackgroundSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Background Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final ImageIcon imageIcon = new ImageIcon("yourFile.gif");
    JTextArea textArea = new JTextArea() {
      Image image = imageIcon.getImage();
      Image grayImage = GrayFilter.createDisabledImage(image);
      {
        setOpaque(false);
      }
      public void paint(Graphics g) {
        g.drawImage(grayImage, 0, 0, this);
        super.paint(g);
      }
    };
    JScrollPane scrollPane = new JScrollPane(textArea);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(250, 250);
    frame.setVisible(true);
  }
}





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);
    }
  }
}





GIF Writer

import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
public class ImageConverterGIF {
  public static void main(String[] args) throws Exception {
    String imageFilePath = "C:/myBmp.bmp";
    String gifFilePath = "C:/myPic.gif";
    File inputFile = new File(imageFilePath);
    BufferedImage image = ImageIO.read(inputFile);
    File outputFile = new File(gifFilePath);
    ImageIO.write(image, "GIF", outputFile);
  }
}





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);
  }
}





JTextComponent: the parent class for all the components used as textual views.

  1. JTextComponent describes the common behavior shared by all text components:
  2. a Highlighter for selection support,
  3. a Caret for navigation throughout the content,
  4. a set of commands supported through the actions property (an array of Action implementers),
  5. a set of key bindings through a Keymap or InputMap/ActionMap combination,
  6. an implementation of the Scrollable interface so that each of the specific text components can be placed within a JScrollPane, and the text stored within the component.


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);
      }
    });
  }
}





Listening to JTextField Events with an KeyListener

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class AddingActionCommandActionListenerSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    KeyListener keyListener = new KeyListener() {
      public void keyPressed(KeyEvent keyEvent) {
        printIt("Pressed", keyEvent);
      }
      public void keyReleased(KeyEvent keyEvent) {
        printIt("Released", keyEvent);
      }
      public void keyTyped(KeyEvent keyEvent) {
        printIt("Typed", keyEvent);
      }
      private void printIt(String title, KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        String keyText = KeyEvent.getKeyText(keyCode);
        System.out.println(title + " : " + keyText);
      }
    };
    textField.addKeyListener(keyListener);
    textField.addKeyListener(keyListener);
    
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Listening to Text Components Events with a DocumentListener

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class AddingDocumentListenerJTextFieldSample {
  public static void main(String args[]) {
    final JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    DocumentListener documentListener = new DocumentListener() {
      public void changedUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }
      public void insertUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }
      public void removeUpdate(DocumentEvent documentEvent) {
        printIt(documentEvent);
      }
      private void printIt(DocumentEvent documentEvent) {
        DocumentEvent.EventType type = documentEvent.getType();
        String typeString = null;
        if (type.equals(DocumentEvent.EventType.CHANGE)) {
          typeString = "Change";
        }  else if (type.equals(DocumentEvent.EventType.INSERT)) {
          typeString = "Insert";
        }  else if (type.equals(DocumentEvent.EventType.REMOVE)) {
          typeString = "Remove";
        }
        System.out.print("Type : " + typeString);
        Document source = documentEvent.getDocument();
        int length = source.getLength();
        System.out.println("Length: " + length);
      }
    };
    textField.getDocument().addDocumentListener(documentListener);
    
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Listening to Text Components Events with an ActionListener

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class AddingActionCommandActionListenerSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Command: " + actionEvent.getActionCommand());
      }
    };
    textField.setActionCommand("Yo");
    textField.addActionListener(actionListener);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Listening to Text Components Events with an InputVerifier

Do field-level validation of a JTextField. Before focus moves out of a text component, the verifier runs. If not valid, the verifier rejects the change and keeps input focus within the given component.



import java.awt.BorderLayout;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.text.JTextComponent;
public class AddingActionCommandActionListenerSample {
  public static void main(String args[]) {
    final JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    frame.add(new JTextField(), BorderLayout.SOUTH);
    InputVerifier verifier = new InputVerifier() {
      public boolean verify(JComponent input) {
        final JTextComponent source = (JTextComponent)input;
        String text = source.getText();
        if ((text.length() != 0) && !(text.equals("Exit"))) {
              JOptionPane.showMessageDialog (frame, "Can"t leave.",
                "Error Dialog", JOptionPane.ERROR_MESSAGE);
          return false;
        } else {
          return true;
        }
      }
    };
    textField.setInputVerifier(verifier);
    
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Loading and Saving Content

import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LabelSampleLoadText {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Label Focus Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JLabel label = new JLabel("Name: ");
    label.setDisplayedMnemonic(KeyEvent.VK_N);
    JTextField textField = new JTextField();
    label.setLabelFor(textField);
    panel.add(label, BorderLayout.WEST);
    panel.add(textField, BorderLayout.CENTER);
    frame.add(panel, BorderLayout.NORTH);
    frame.add(new JButton("Somewhere Else"), BorderLayout.SOUTH);
    frame.setSize(250, 150);
    frame.setVisible(true);
    FileReader reader = null;
    try {
      String filename = "test.txt";
      reader = new FileReader(filename);
      textField.read(reader, filename);
    } catch (IOException exception) {
      System.err.println("Load oops");
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException exception) {
          System.err.println("Error closing reader");
          exception.printStackTrace();
        }
      }
    }
  }
}





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 the Default Action of a JTextComponent

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea component = new JTextArea();
    Action defAction = findDefaultAction(component);
    component.getKeymap().setDefaultAction(new MyDefaultAction(defAction));
  }
  public static Action findDefaultAction(JTextComponent c) {
    Keymap kmap = c.getKeymap();
    if (kmap.getDefaultAction() != null) {
      return kmap.getDefaultAction();
    }
    kmap = kmap.getResolveParent();
    while (kmap != null) {
      if (kmap.getDefaultAction() != null) {
        return kmap.getDefaultAction();
      }
      kmap = kmap.getResolveParent();
    }
    return null;
  }
}
class MyDefaultAction extends AbstractAction {
  Action defAction;
  public MyDefaultAction(Action a) {
    super("My Default Action");
    defAction = a;
  }
  public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand() != null) {
      String command = e.getActionCommand();
      if (command != null) {
        command = command.toUpperCase();
      }
      e = new ActionEvent(e.getSource(), e.getID(), command, e.getModifiers());
    }
    if (defAction != null) {
      defAction.actionPerformed(e);
    }
  }
}





Register Keyboard action: registerKeyboardAction

import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
public class PopupSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Popup Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JPopupMenu popup = new JPopupMenu();
    JMenuItem menuItem1 = new JMenuItem("Option 1");
    popup.add(menuItem1);
    JMenuItem menuItem2 = new JMenuItem("Option 2");
    popup.add(menuItem2);
    final JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        try {
          int dotPosition = textField.getCaretPosition();
          Rectangle popupLocation = textField.modelToView(dotPosition);
          popup.show(textField, popupLocation.x, popupLocation.y);
        } catch (BadLocationException badLocationException) {
          System.err.println("Oops");
        }
      }
    };
    KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0, false);
    textField.registerKeyboardAction(actionListener, keystroke, JComponent.WHEN_FOCUSED);
    frame.add(new JLabel("Press "." to activate Popup menu"), BorderLayout.SOUTH);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





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]);
      }
    }
  }
}





Remove Key action from Text component

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.Keymap;
public class DefaultSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Default Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField textField = new JTextField();
    frame.add(textField, BorderLayout.NORTH);
    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getActionCommand() + " selected");
      }
    };
    JPanel panel = new JPanel();
    JButton defaultButton = new JButton("Default Button");
    defaultButton.addActionListener(actionListener);
    panel.add(defaultButton);
    JButton otherButton = new JButton("Other Button");
    otherButton.addActionListener(actionListener);
    panel.add(otherButton);
    frame.add(panel, BorderLayout.SOUTH);
    Keymap keymap = textField.getKeymap();
    KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
    keymap.removeKeyStrokeBinding(keystroke);
    frame.getRootPane().setDefaultButton(defaultButton);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Restricting Caret Movement: NavigationFilter

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.text.NavigationFilter;
import javax.swing.text.Position;
public class NavigationSample {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Navigation Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    frame.add(scrollPane, BorderLayout.CENTER);
    NavigationFilter filter = new NavigationFilter() {
      public void setDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) {
        System.out.println("Setting: " + dot);
        fb.setDot(dot, bias);
      }
      public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) {
        System.out.println("Moving: " + dot);
        fb.setDot(dot, bias);
      }
    };
    textArea.setNavigationFilter(filter);
    frame.setSize(250, 150);
    frame.setVisible(true);
  }
}





Set the caret color

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);
    }
    // Set the caret color
    c.setCaretColor(Color.red);
  }
}





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);
  }
}





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);
  }
}





Share Document

import java.awt.Container;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class SharedModel {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Shared Model");
    JTextArea areaFiftyOne = new JTextArea();
    JTextArea areaFiftyTwo = new JTextArea();
    areaFiftyTwo.setDocument(areaFiftyOne.getDocument());
    JTextArea areaFiftyThree = new JTextArea();
    areaFiftyThree.setDocument(areaFiftyOne.getDocument());
    frame.setLayout(new GridLayout(3, 1));
    frame.add(new JScrollPane(areaFiftyOne));
    frame.add(new JScrollPane(areaFiftyTwo));
    frame.add(new JScrollPane(areaFiftyThree));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(300, 300);
    frame.setVisible(true);
  }
}





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());
  }
}





TextAction Name Constants

  1. DefaultEditorKit.backwardAction
  2. DefaultEditorKit.previousWordAction
  3. DefaultEditorKit.beepAction
  4. DefaultEditorKit.readOnlyAction
  5. DefaultEditorKit.beginAction
  6. DefaultEditorKit.selectAllAction
  7. DefaultEditorKit.beginLineAction
  8. DefaultEditorKit.selectionBackwardAction
  9. DefaultEditorKit.beginParagraphAction
  10. DefaultEditorKit.selectionBeginAction
  11. DefaultEditorKit.beginWordAction
  12. DefaultEditorKit.selectionBeginLineAction
  13. DefaultEditorKit.copyAction
  14. DefaultEditorKit.selectionBeginParagraphAction
  15. DefaultEditorKit.cutAction
  16. DefaultEditorKit.selectionBeginWordAction
  17. DefaultEditorKit.defaultKeyTypedAction
  18. DefaultEditorKit.selectionDownAction
  19. DefaultEditorKit.deleteNextCharAction
  20. DefaultEditorKit.selectionEndAction
  21. DefaultEditorKit.deletePrevCharAction
  22. DefaultEditorKit.selectionEndLineAction
  23. DefaultEditorKit.downAction
  24. DefaultEditorKit.selectionEndParagraphAction
  25. DefaultEditorKit.endAction
  26. DefaultEditorKit.selectionEndWordAction
  27. DefaultEditorKit.endLineAction
  28. DefaultEditorKit.selectionForwardAction
  29. DefaultEditorKit.endParagraphAction
  30. DefaultEditorKit.selectionNextWordAction
  31. DefaultEditorKit.endWordAction
  32. DefaultEditorKit.selectionPreviousWordAction
  33. DefaultEditorKit.forwardAction
  34. DefaultEditorKit.selectionUpAction
  35. DefaultEditorKit.insertBreakAction
  36. DefaultEditorKit.selectLineAction
  37. DefaultEditorKit.insertContentAction
  38. DefaultEditorKit.selectParagraphAction
  39. DefaultEditorKit.insertTabAction
  40. DefaultEditorKit.selectWordAction
  41. DefaultEditorKit.nextWordAction
  42. DefaultEditorKit.upAction
  43. DefaultEditorKit.pageDownAction
  44. DefaultEditorKit.writableAction
  45. DefaultEditorKit.pageUpAction
  46. JTextField.notifyAction
  47. DefaultEditorKit.pasteAction


Text Component Printing

import java.awt.BorderLayout;
import java.text.MessageFormat;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TextComponentDemo {
  public static void main(String[] args) throws Exception {
    final JTextArea textArea = new JTextArea();
    textArea.setText("text");
    JScrollPane jScrollPane = new JScrollPane(textArea);
    final MessageFormat header = new MessageFormat("My Header");
    final MessageFormat footer = new MessageFormat("My Footer");
    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(jScrollPane, BorderLayout.CENTER);
    JFrame frame = new JFrame();
    frame.setTitle("Text-component Printing Demo");
    frame.setSize(400, 200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(contentPane);
    frame.setVisible(true);
    textArea.print(header, footer, true, null, null, true);
  }
}





Text component supports both cut, copy and paste (using the DefaultEditorKit"s built-in actions) and drag and drop

/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * TextCutPaste.java requires the following file:
 *     TextTransferHandler.java
 */
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.KeyEvent;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Position;
/**
 * Example code that shows a text component that supports both cut, copy and
 * paste (using the DefaultEditorKit"s built-in actions) and drag and drop.
 */
public class TextCutPaste extends JPanel {
  TextTransferHandler th;
  public TextCutPaste() {
    super(new BorderLayout());
    setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
    // Create the transfer handler.
    TextTransferHandler th = new TextTransferHandler();
    // Create some text fields.
    JPanel buttonPanel = new JPanel(new GridLayout(3, 1));
    JTextField textField = new JTextField("Cut, copy and paste...", 30);
    textField.setTransferHandler(th);
    textField.setDragEnabled(true);
    buttonPanel.add(textField);
    textField = new JTextField("or drag and drop...", 30);
    textField.setTransferHandler(th);
    textField.setDragEnabled(true);
    buttonPanel.add(textField);
    textField = new JTextField("from any of these text fields.", 30);
    textField.setTransferHandler(th);
    textField.setDragEnabled(true);
    buttonPanel.add(textField);
    add(buttonPanel, BorderLayout.CENTER);
  }
  /**
   * Create an Edit menu to support cut/copy/paste.
   */
  public JMenuBar createMenuBar() {
    JMenuItem menuItem = null;
    JMenuBar menuBar = new JMenuBar();
    JMenu mainMenu = new JMenu("Edit");
    mainMenu.setMnemonic(KeyEvent.VK_E);
    menuItem = new JMenuItem(new DefaultEditorKit.CutAction());
    menuItem.setText("Cut");
    menuItem.setMnemonic(KeyEvent.VK_T);
    mainMenu.add(menuItem);
    menuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
    menuItem.setText("Copy");
    menuItem.setMnemonic(KeyEvent.VK_C);
    mainMenu.add(menuItem);
    menuItem = new JMenuItem(new DefaultEditorKit.PasteAction());
    menuItem.setText("Paste");
    menuItem.setMnemonic(KeyEvent.VK_P);
    mainMenu.add(menuItem);
    menuBar.add(mainMenu);
    return menuBar;
  }
  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("TextCutPaste");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the menu bar and content pane.
    TextCutPaste demo = new TextCutPaste();
    frame.setJMenuBar(demo.createMenuBar());
    demo.setOpaque(true); // content panes must be opaque
    frame.setContentPane(demo);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }
  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application"s GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        // Turn off metal"s use of bold fonts
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        createAndShowGUI();
      }
    });
  }
}
/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *  - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *  - Neither the name of Sun Microsystems nor the names of its contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * TextTransferHandler.java is used by the TextCutPaste.java example.
 */
/**
 * An implementation of TransferHandler that adds support for the import and
 * export of text using drag and drop and cut/copy/paste.
 */
class TextTransferHandler extends TransferHandler {
  // Start and end position in the source text.
  // We need this information when performing a MOVE
  // in order to remove the dragged text from the source.
  Position p0 = null, p1 = null;
  /**
   * Perform the actual import. This method supports both drag and drop and
   * cut/copy/paste.
   */
  public boolean importData(TransferHandler.TransferSupport support) {
    // If we can"t handle the import, bail now.
    if (!canImport(support)) {
      return false;
    }
    // Fetch the data -- bail if this fails
    String data;
    try {
      data = (String) support.getTransferable().getTransferData(
          DataFlavor.stringFlavor);
    } catch (UnsupportedFlavorException e) {
      return false;
    } catch (java.io.IOException e) {
      return false;
    }
    JTextField tc = (JTextField) support.getComponent();
    tc.replaceSelection(data);
    return true;
  }
  /**
   * Bundle up the data for export.
   */
  protected Transferable createTransferable(JComponent c) {
    JTextField source = (JTextField) c;
    int start = source.getSelectionStart();
    int end = source.getSelectionEnd();
    Document doc = source.getDocument();
    if (start == end) {
      return null;
    }
    try {
      p0 = doc.createPosition(start);
      p1 = doc.createPosition(end);
    } catch (BadLocationException e) {
      System.out
          .println("Can"t create position - unable to remove text from source.");
    }
    String data = source.getSelectedText();
    return new StringSelection(data);
  }
  /**
   * These text fields handle both copy and move actions.
   */
  public int getSourceActions(JComponent c) {
    return COPY_OR_MOVE;
  }
  /**
   * When the export is complete, remove the old text if the action was a move.
   */
  protected void exportDone(JComponent c, Transferable data, int action) {
    if (action != MOVE) {
      return;
    }
    if ((p0 != null) && (p1 != null) && (p0.getOffset() != p1.getOffset())) {
      try {
        JTextComponent tc = (JTextComponent) c;
        tc.getDocument()
            .remove(p0.getOffset(), p1.getOffset() - p0.getOffset());
      } catch (BadLocationException e) {
        System.out.println("Can"t remove text from source.");
      }
    }
  }
  /**
   * We only support importing strings.
   */
  public boolean canImport(TransferHandler.TransferSupport support) {
    // we only import Strings
    if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
      return false;
    }
    return true;
  }
}





Using Text Component Actions

import java.awt.BorderLayout;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.text.DefaultEditorKit;
public class UseActionsFromTextComponents {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Use TextAction");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JTextArea leftArea = new JTextArea();
    final JTextArea rightArea = new JTextArea();
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(leftArea),
        new JScrollPane(rightArea));
    splitPane.setDividerLocation(.5);
    
    JMenuBar menuBar = new JMenuBar();
    frame.setJMenuBar(menuBar);
    JMenu menu = new JMenu("Options");
    menuBar.add(menu);
    JMenuItem menuItem;
    Action readAction = leftArea.getActionMap().get(DefaultEditorKit.readOnlyAction);
    menuItem = menu.add(readAction);
    menuItem.setText("Make read-only");
    Action writeAction = leftArea.getActionMap().get(DefaultEditorKit.writableAction);
    menuItem = menu.add(writeAction);
    menuItem.setText("Make writable");
    menu.addSeparator();
    Action cutAction = leftArea.getActionMap().get(DefaultEditorKit.cutAction);
    menuItem = menu.add(cutAction);
    menuItem.setText("Cut");
    Action copyAction = leftArea.getActionMap().get(DefaultEditorKit.copyAction);
    menuItem = menu.add(copyAction);
    menuItem.setText("Copy");
    Action pasteAction = leftArea.getActionMap().get(DefaultEditorKit.pasteAction);
    menuItem = menu.add(pasteAction);
    menuItem.setText("Paste");
    frame.add(splitPane, BorderLayout.CENTER);
    frame.setSize(400, 250);
    frame.setVisible(true);
  }
}





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();
  }
}