Java Tutorial/Swing/JTextArea

Материал из Java эксперт
Перейти к: навигация, поиск

Append some text to JTextArea

import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) {
    JTextArea ta = new JTextArea("Initial Text");
    ta.append("some text");
  }
}





Copy selected text from one text area to another

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class Main extends JFrame {
  private JTextArea t1 = new JTextArea("this is a test", 10, 15), t2;
  private JButton copy = new JButton("Copy >>>");
  public Main() {
    Box b = Box.createHorizontalBox();    
    b.add(new JScrollPane(t1));    
    copy.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        t2.setText(t1.getSelectedText());
      }
    });
    b.add(copy);
    t2 = new JTextArea(10, 15);
    t2.setEditable(false);
    b.add(new JScrollPane(t2));
    add(b); 
    setSize(425, 200);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  public static void main(String args[]) {
    new Main();
  }
}





Customizing a JTextArea Look and Feel

Property StringObject TypeTextArea.actionMapActionMapTextArea.backgroundColorTextArea.borderBorderTextArea.caretAspectRatioNumberTextArea.caretBlinkRateIntegerTextArea.caretForegroundColorTextArea.focusInputMapInputMapTextArea.fontFontTextArea.foregroundColorTextArea.inactiveForegroundColorTextArea.keyBindingsKeyBinding[ ]TextArea.marginInsetsTextArea.selectionBackgroundColorTextArea.selectionForegroundColorTextAreaUIString


Delete the first 5 characters

import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) {
    JTextArea ta = new JTextArea("Initial Text");
    int start = 0;
    int end = 5;
    ta.replaceRange(null, start, end);
  }
}





Enumerate the content elements with a ElementIterator

import javax.swing.JTextArea;
import javax.swing.text.Document;
import javax.swing.text.Element;
import javax.swing.text.ElementIterator;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea textArea = new JTextArea("word1 word2\nword3\nword4");
    Document doc = textArea.getDocument();
    ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
    Element e;
    while ((e = it.next()) != null) {
      if (e.isLeaf()) {
        int rangeStart = e.getStartOffset();
        int rangeEnd = e.getEndOffset();
        String line = textArea.getText(rangeStart, rangeEnd - rangeStart);
        System.out.println(line);
      }
    }
  }
}





Enumerating the Lines in a JTextArea Component

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





Hello in Japanese

import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class HelloInJapanese extends JPanel {
  static JFrame frame;
  static String helloInJapanese = "\u4eca\u65e5\u306f.";
  public HelloInJapanese(String characters) {
    JTextArea area = new JTextArea(characters, 2, 30);
    area.setFont(new Font("Bitstream Cyberbit", Font.PLAIN, 20));
    area.setLineWrap(true);
    JScrollPane scrollpane = new JScrollPane(area);
    add(scrollpane);
  }
  public static void main(String argv[]) {
    HelloInJapanese japanesePanel = new HelloInJapanese(helloInJapanese);
    frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add("Center", japanesePanel);
    frame.pack();
    frame.setVisible(true);
  }
}





Highlight of discontinous string

import javax.swing.JTextArea;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
public class Main {
  public static void main(String args[]) {
    JTextArea area = new JTextArea(5, 20);
    area.setText("this is a test.");
    String charsToHighlight = "aeiouAEIOU";
    Highlighter h = area.getHighlighter();
    h.removeAllHighlights();
    String text = area.getText().toUpperCase();
    for (int i = 0; i < text.length(); i += 1) {
      char ch = text.charAt(i);
      if (charsToHighlight.indexOf(ch) >= 0)
        try {
          h.addHighlight(i, i + 1, DefaultHighlighter.DefaultPainter);
        } catch (Exception ble) {
        }
    }
  }
}





Insert some text after the 5th character

import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) {
    JTextArea ta = new JTextArea("Initial Text");
    int pos = 5;
    ta.insert("some text", pos);
  }
}





JTextArea: for multiple-line input.

Put JTextArea within a JScrollPane to allow a user to properly scroll through the contents of a JTextArea.



JTextArea textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
content.add(scrollPane);





Modifying Text in a JTextArea Component

import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) {
    // Create the text area
    JTextArea ta = new JTextArea("Initial Text");
    // Insert some text at the beginning
    int pos = 0;
    ta.insert("some text", pos);
  }
}





Moving the Focus with the TAB Key in a JTextArea Component

import java.awt.ruponent;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) throws Exception {
    JTextArea component = new JTextArea();
    NextFocusAction nextFocusAction = new NextFocusAction();
    PrevFocusAction prevFocusAction = new PrevFocusAction();
    
    component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
    component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
  }
}
class NextFocusAction extends AbstractAction{
  public NextFocusAction(){
    super("Move Focus Forwards");
  }
  public void actionPerformed(ActionEvent evt) {
    ((Component) evt.getSource()).transferFocus();
  }
}
class PrevFocusAction extends AbstractAction {
  public PrevFocusAction(){
    super("Move Focus Backwards");
  }
  public void actionPerformed(ActionEvent evt) {
    ((Component) evt.getSource()).transferFocusBackward();
  }
}





Replace the first 3 characters with some text

import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) {
    JTextArea ta = new JTextArea("Initial Text");
    int start = 0;
    int end = 3;
    ta.replaceRange("new text", start, end);
  }
}





Set font for I18N to JTextArea

import java.awt.Font;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class JTextAreaI18N extends JFrame {
  String davidMessage = "\u05E9\u05DC\u05D5\u05DD \u05E2\u05D5\u05DC\u05DD";
  public JTextAreaI18N() {
    GraphicsEnvironment.getLocalGraphicsEnvironment();
    JTextArea textArea = new JTextArea(davidMessage);
    textArea.setFont(new Font("LucidaSans", Font.PLAIN, 40));
    this.getContentPane().add(textArea);
    textArea.setVisible(true);
  }
  public static void main(String[] args) {
    JFrame frame = new JTextAreaI18N();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }
}





Setting JTextArea Line Wrap and Wrap Style

JTextArea textArea = new JTextArea("...");
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);





Setting text drag in a JTextArea

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    JTextArea textarea = new JTextArea();
    textarea.setDragEnabled(true);
    textarea.setText("Drag target");
    frame.getContentPane().add(BorderLayout.CENTER, textarea);
    JTextField textarea1 = new JTextField();
    textarea1.setText("Drop target");
    frame.getContentPane().add(BorderLayout.SOUTH, textarea1);
    frame.setSize(500, 300);
    frame.setVisible(true);
    frame.setLocation(100, 100);
  }
}





Setting the Tab Size of a JTextArea Component

import java.awt.Font;
import javax.swing.JTextArea;
public class Main {
  public static void main(String[] argv) {
    JTextArea textarea = new JTextArea();
    // Get the default tab size
    int tabSize = textarea.getTabSize(); // 8
    // Change the tab size
    tabSize = 4;
    textarea.setTabSize(tabSize);
    Font font = textarea.getFont();
    System.out.println(font);
  }
}





Using Actions with Text Components: JTextArea

import java.util.Arrays;
import java.util.ruparator;
import javax.swing.Action;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
public class ListActionsJTextArea {
  public static void main(String args[]) {
    JTextComponent component = new JTextArea();
    // Process action list
    Action actions[] = component.getActions();
    // Define comparator to sort actions
    Comparator<Action> comparator = new Comparator<Action>() {
      public int compare(Action a1, Action a2) {
        String firstName = (String) a1.getValue(Action.NAME);
        String secondName = (String) a2.getValue(Action.NAME);
        return firstName.rupareTo(secondName);
      }
    };
    Arrays.sort(actions, comparator);
    int count = actions.length;
    System.out.println("Count: " + count);
    for (int i = 0; i < count; i++) {
      System.out.printf("%28s : %s\n",actions[i].getValue(Action.NAME),actions[i].getClass().getName());
    }
  }
}



Count: 53
                        beep : javax.swing.text.DefaultEditorKit$BeepAction
              caret-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
                 caret-begin : javax.swing.text.DefaultEditorKit$BeginAction
            caret-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction
       caret-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction
            caret-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction
                  caret-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
                   caret-end : javax.swing.text.DefaultEditorKit$EndAction
              caret-end-line : javax.swing.text.DefaultEditorKit$EndLineAction
         caret-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction
              caret-end-word : javax.swing.text.DefaultEditorKit$EndWordAction
               caret-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
             caret-next-word : javax.swing.text.DefaultEditorKit$NextWordAction
         caret-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction
                    caret-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
           copy-to-clipboard : javax.swing.text.DefaultEditorKit$CopyAction
            cut-to-clipboard : javax.swing.text.DefaultEditorKit$CutAction
               default-typed : javax.swing.text.DefaultEditorKit$DefaultKeyTypedAction
                 delete-next : javax.swing.text.DefaultEditorKit$DeleteNextCharAction
             delete-previous : javax.swing.text.DefaultEditorKit$DeletePrevCharAction
                  dump-model : javax.swing.text.DefaultEditorKit$DumpModelAction
                insert-break : javax.swing.text.DefaultEditorKit$InsertBreakAction
              insert-content : javax.swing.text.DefaultEditorKit$InsertContentAction
                  insert-tab : javax.swing.text.DefaultEditorKit$InsertTabAction
                   page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction
                     page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction
        paste-from-clipboard : javax.swing.text.DefaultEditorKit$PasteAction
                  select-all : javax.swing.text.DefaultEditorKit$SelectAllAction
                 select-line : javax.swing.text.DefaultEditorKit$SelectLineAction
            select-paragraph : javax.swing.text.DefaultEditorKit$SelectParagraphAction
                 select-word : javax.swing.text.DefaultEditorKit$SelectWordAction
          selection-backward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
             selection-begin : javax.swing.text.DefaultEditorKit$BeginAction
        selection-begin-line : javax.swing.text.DefaultEditorKit$BeginLineAction
   selection-begin-paragraph : javax.swing.text.DefaultEditorKit$BeginParagraphAction
        selection-begin-word : javax.swing.text.DefaultEditorKit$BeginWordAction
              selection-down : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
               selection-end : javax.swing.text.DefaultEditorKit$EndAction
          selection-end-line : javax.swing.text.DefaultEditorKit$EndLineAction
     selection-end-paragraph : javax.swing.text.DefaultEditorKit$EndParagraphAction
          selection-end-word : javax.swing.text.DefaultEditorKit$EndWordAction
           selection-forward : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
         selection-next-word : javax.swing.text.DefaultEditorKit$NextWordAction
         selection-page-down : javax.swing.text.DefaultEditorKit$VerticalPageAction
         selection-page-left : javax.swing.text.DefaultEditorKit$PageAction
        selection-page-right : javax.swing.text.DefaultEditorKit$PageAction
           selection-page-up : javax.swing.text.DefaultEditorKit$VerticalPageAction
     selection-previous-word : javax.swing.text.DefaultEditorKit$PreviousWordAction
                selection-up : javax.swing.text.DefaultEditorKit$NextVisualPositionAction
               set-read-only : javax.swing.text.DefaultEditorKit$ReadOnlyAction
                set-writable : javax.swing.text.DefaultEditorKit$WritableAction
 toggle-componentOrientation : javax.swing.text.DefaultEditorKit$ToggleComponentOrientationAction
                    unselect : javax.swing.text.DefaultEditorKit$UnselectAction


Using JTextArea

import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class JTextAreaTest {
  public static void main(String[] args) {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("JTextArea Test");
    frame.setLayout(new FlowLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    String text = "A JTextArea object represents a multiline area for displaying text. "
        + "You can change the number of lines that can be displayed at a time, "
        + "as well as the number of columns. You can wrap lines and words too. "
        + "You can also put your JTextArea in a JScrollPane to make it scrollable.";
    JTextArea textAreal = new JTextArea(text, 5, 10);
    textAreal.setPreferredSize(new Dimension(100, 100));
    JTextArea textArea2 = new JTextArea(text, 5, 10);
    textArea2.setPreferredSize(new Dimension(100, 100));
    JScrollPane scrollPane = new JScrollPane(textArea2, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
        JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    textAreal.setLineWrap(true);
    textArea2.setLineWrap(true);
    frame.add(textAreal);
    frame.add(scrollPane);
    frame.pack();
    frame.setVisible(true);
  }
}