Java by API/javax.swing.text/Document

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

Document: addDocumentListener(DocumentListener listener)

 

import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class Main {
  JButton button = new JButton("foo");
  JTextField textfield = new JTextField(10);
  Document document;
  public Main() {
    document = textfield.getDocument();
    document.addDocumentListener(new JButtonStateController());
  }
  class JButtonStateController implements DocumentListener {
    JButtonStateController() {
    }
    public void changedUpdate(DocumentEvent e) {
      disableIfEmpty(e);
    }
    public void insertUpdate(DocumentEvent e) {
      disableIfEmpty(e);
    }
    public void removeUpdate(DocumentEvent e) {
      disableIfEmpty(e);
    }
    public void disableIfEmpty(DocumentEvent e) {
      button.setEnabled(e.getDocument().getLength() > 0);
    }
  }
}





Document: addUndoableEditListener(UndoableEditListener listener)

 
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoableEdit;
public class UndoStyleFrame extends JFrame {
  protected UndoAct undoAction = new UndoAct();
  protected RedoAct redoAction = new RedoAct();
  public UndoStyleFrame() {
    super();
    setTitle("UndoStyleFrame");
    JTextPane textPane = new JTextPane();
    textPane.getDocument().addUndoableEditListener(undoAction);
    textPane.getDocument().addUndoableEditListener(redoAction);
    JMenu editMenu = new JMenu("Edit");
    editMenu.add(new JMenuItem(undoAction));
    editMenu.add(new JMenuItem(redoAction));
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(editMenu);
    setJMenuBar(menuBar);
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(new JButton(undoAction));
    buttonPanel.add(new JButton(redoAction));
    
    getContentPane().add(textPane, "Center");
    getContentPane().add(buttonPanel, "South");
  }
  public class UndoAct extends AbstractAction implements UndoableEditListener {
    private UndoableEdit edit;
    public UndoAct() {
      super("Undo");
      setEnabled(false);
    }
    public void updateEnabled() {
      setEnabled(edit.canUndo());
    }
    public void undoableEditHappened(UndoableEditEvent event) {
      edit = event.getEdit();
      putValue(NAME, edit.getUndoPresentationName());
      updateEnabled();
    }
    public void actionPerformed(ActionEvent ae) {
      edit.undo();
      updateEnabled(); 
      redoAction.updateEnabled(); 
    }
  }
  public class RedoAct extends AbstractAction implements UndoableEditListener {
    private UndoableEdit edit;
    public RedoAct() {
      super("Redo");
      setEnabled(false);
    }
    public void updateEnabled() {
      setEnabled(edit.canRedo());
    }
    public void undoableEditHappened(UndoableEditEvent event) {
      edit = event.getEdit();
      putValue(NAME, edit.getRedoPresentationName());
      updateEnabled();
    }
    public void actionPerformed(ActionEvent ae) {
      edit.redo();
      updateEnabled(); 
      undoAction.updateEnabled();
    }
  }
  public static void main(String[] args) {
    JFrame frame = new UndoStyleFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
  }
}





Document: dump(PrintStream out)

 
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
public class Main {
  public static void main(String[] args) {
    JFrame f = new JFrame("Text Field Elements");
    JTextField tf = new JTextField(32);
    tf.setText("That"s one small step for man...");
    f.getContentPane().add(tf);
    f.pack();
    f.setVisible(true);
    ((AbstractDocument) tf.getDocument()).dump(System.out);
  }
}





Document: getDefaultRootElement()

 

import javax.swing.JTextArea;
import javax.swing.text.Element;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    Element paragraph = textArea.getDocument().getDefaultRootElement();
    int contentCount = paragraph.getElementCount();
    for (int i = 0; i < contentCount; i++) {
      Element e = paragraph.getElement(i);
      int rangeStart = e.getStartOffset();
      int rangeEnd = e.getEndOffset();
      String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
      System.out.println(line);
    }
  }
}





Document: getLength()

 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    frame.add(new JTextField(), BorderLayout.SOUTH);
    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();
        try {
          System.out.println("Contents: " + source.getText(0, length));
        } catch (BadLocationException badLocationException) {
          System.out.println("Contents: Unknown");
        }
      }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    
    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}





Document: getText(int offset, int length)

 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField nameTextField = new JTextField();
    frame.add(nameTextField, BorderLayout.NORTH);
    frame.add(new JTextField(), BorderLayout.SOUTH);
    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();
        try {
          System.out.println("Contents: " + source.getText(0, length));
        } catch (BadLocationException badLocationException) {
          System.out.println("Contents: Unknown");
        }
      }
    };
    nameTextField.getDocument().addDocumentListener(documentListener);
    
    frame.setSize(250, 100);
    frame.setVisible(true);
  }
}





Document: insertString(int offset, String str, AttributeSet a)

 
import java.awt.BorderLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;
public class MainClass {
  public static void main(String args[]) throws Exception {
    JFrame frame = new JFrame("TextPane Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    StyleContext context = new StyleContext();
    StyledDocument document = new DefaultStyledDocument(context);
    Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
    StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
    StyleConstants.setFontSize(style, 14);
    StyleConstants.setSpaceAbove(style, 4);
    StyleConstants.setSpaceBelow(style, 4);
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    StyleConstants.setBold(attributes, true);
    StyleConstants.setItalic(attributes, true);
    // Third style for icon/component
    Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
    Icon icon = new ImageIcon("Computer.gif");
    JLabel label = new JLabel(icon);
    StyleConstants.setComponent(labelStyle, label);
    try {
      document.insertString(document.getLength(), "Hello www.jexp.ru", attributes);
      document.insertString(document.getLength(), "Ignored", labelStyle);
    } catch (BadLocationException badLocationException) {
      System.err.println("Oops");
    }
    JTextPane textPane = new JTextPane(document);
    textPane.setEditable(false);
    JScrollPane scrollPane = new JScrollPane(textPane);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
  }
}





Document: remove(int offs, int len)

 
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Hashtable;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultEditorKit;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;
import javax.swing.text.TextAction;
import javax.swing.text.Utilities;
public class Main {
  public static void main(String[] args) {
    JTextArea area = new JTextArea(6, 32);
    Keymap parent = area.getKeymap();
    Keymap newmap = JTextComponent.addKeymap("KeymapExampleMap", parent);
    KeyStroke u = KeyStroke.getKeyStroke(KeyEvent.VK_U,
        InputEvent.CTRL_MASK);
    Action actionU = new UpWord();
    newmap.addActionForKeyStroke(u, actionU);
    Action actionList[] = area.getActions();
    Hashtable lookup = new Hashtable();
    for (int j = 0; j < actionList.length; j += 1)
      lookup.put(actionList[j].getValue(Action.NAME), actionList[j]);
    KeyStroke L = KeyStroke.getKeyStroke(KeyEvent.VK_L,
        InputEvent.CTRL_MASK);
    Action actionL = (Action) lookup.get(DefaultEditorKit.selectLineAction);
    newmap.addActionForKeyStroke(L, actionL);
    KeyStroke W = KeyStroke.getKeyStroke(KeyEvent.VK_W,
        InputEvent.CTRL_MASK);
    Action actionW = (Action) lookup.get(DefaultEditorKit.selectWordAction);
    newmap.addActionForKeyStroke(W, actionW);
    area.setKeymap(newmap);
    JFrame f = new JFrame("KeymapExample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
    area.setText("This is a test.");
    f.pack();
    f.setVisible(true);
  }

}
class UpWord extends TextAction {
  public UpWord() {
    super("uppercase-word-action");
  }
  public void actionPerformed(ActionEvent e) {
    JTextComponent comp = getTextComponent(e);
    if (comp == null)
      return;
    Document doc = comp.getDocument();
    int start = comp.getSelectionStart();
    int end = comp.getSelectionEnd();
    try {
      int left = Utilities.getWordStart(comp, start);
      int right = Utilities.getWordEnd(comp, end);
      String word = doc.getText(left, right - left);
      doc.remove(left, right - left);
      doc.insertString(left, word.toUpperCase(), null);
      comp.setSelectionStart(start);
       comp.setSelectionEnd(end);
    } catch (BadLocationException ble) {
      return;
    }
  }
}