Java by API/javax.swing/JTextComponent

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

JTextComponent: addCaretListener(CaretListener listener)

   <source lang="java">
 

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 MainClass {

 public static void main(String args[]) throws Exception {
   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);
 }

}



 </source>
   
  
 
  



JTextComponent: getActions()

   <source lang="java">
 

//A simple TextAction example. import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JTextArea; public class Main {

 public static void main(String[] args) {
   JTextArea ta = new JTextArea();
   ta.setLineWrap(true);
   Action[] actions = ta.getActions();
   JMenuBar menubar = new JMenuBar();
   JMenu actionmenu = new JMenu("Actions");
   menubar.add(actionmenu);
   JMenu firstHalf = new JMenu("1st Half");
   JMenu secondHalf = new JMenu("2nd Half");
   actionmenu.add(firstHalf);
   actionmenu.add(secondHalf);
   int mid = actions.length / 2;
   for (int i = 0; i < mid; i++) {
     firstHalf.add(actions[i]);
   }
   for (int i = mid; i < actions.length; i++) {
     secondHalf.add(actions[i]);
   }
   // Show it . . .
   JFrame f = new JFrame();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.getContentPane().add(ta);
   f.setJMenuBar(menubar);
   f.setSize(300, 200);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



JTextComponent: getCaretPosition()

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: getDocument()

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: getHighlighter()

   <source lang="java">
 

import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; public class Main {

 public static void main(String args[]) throws Exception {
   JFrame frame = new JFrame("MultiHighlight");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextArea comp = new JTextArea(5, 20);
   comp.setText("this is a test");
   frame.getContentPane().add(new JScrollPane(comp), BorderLayout.CENTER);
   String charsToHighlight = "a";
   Highlighter h = comp.getHighlighter();
   h.removeAllHighlights();
   String text = comp.getText().toUpperCase();
   for (int j = 0; j < text.length(); j += 1) {
     char ch = text.charAt(j);
     if (charsToHighlight.indexOf(ch) >= 0)
       h.addHighlight(j, j + 1, DefaultHighlighter.DefaultPainter);
   }
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



JTextComponent: getSelectedText()

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: getText(int offs, int len)

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent.KeyBinding

   <source lang="java">
 

import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Insets; import javax.swing.Icon; import javax.swing.InputMap; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.text.JTextComponent; public class Main {

 public static void main(String[] argv) {
   UIDefaults uidefs = UIManager.getLookAndFeelDefaults();
   String[] keys = (String[]) uidefs.keySet().toArray(new String[0]);
   for (int i = 0; i < keys.length; i++) {
     Object v = uidefs.get(keys[i]);
     if (v instanceof Integer) {
       int intVal = uidefs.getInt(keys[i]);
     } else if (v instanceof Boolean) {
       boolean boolVal = uidefs.getBoolean(keys[i]);
     } else if (v instanceof String) {
       String strVal = uidefs.getString(keys[i]);
     } else if (v instanceof Dimension) {
       Dimension dimVal = uidefs.getDimension(keys[i]);
     } else if (v instanceof Insets) {
       Insets insetsVal = uidefs.getInsets(keys[i]);
     } else if (v instanceof Color) {
       Color colorVal = uidefs.getColor(keys[i]);
     } else if (v instanceof Font) {
       Font fontVal = uidefs.getFont(keys[i]);
     } else if (v instanceof Border) {
       Border borderVal = uidefs.getBorder(keys[i]);
     } else if (v instanceof Icon) {
       Icon iconVal = uidefs.getIcon(keys[i]);
     } else if (v instanceof javax.swing.text.JTextComponent.KeyBinding[]) {
       JTextComponent.KeyBinding[] keyBindsVal = (JTextComponent.KeyBinding[]) uidefs
           .get(keys[i]);
     } else if (v instanceof InputMap) {
       InputMap imapVal = (InputMap) uidefs.get(keys[i]);
     } else {
       System.out.println("Unknown type"); 
     }
   }
 }

}


 </source>
   
  
 
  



JTextComponent: moveCaretPosition(int pos)

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: print(MessageFormat headerFormat, MessageFormat footerFormat, boolean showPrintDialog, PrintService service, PrintRequestAttributeSet attributes, boolean interactive)

   <source lang="java">
 

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 Main {

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

}


 </source>
   
  
 
  



JTextComponent: read(Reader in, Object desc)

   <source lang="java">
 

import java.awt.BorderLayout; import java.io.FileReader; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JTextField; 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);
   
   FileReader reader = null;
   try {
     reader = new FileReader("fileName.txt");
     nameTextField.read(reader, "fileName.txt");
   } catch (IOException exception) {
     System.err.println("Load oops");
     exception.printStackTrace();
   } finally {
     if (reader != null) {
       try {
         reader.close();
       } catch (IOException exception) {
         System.err.println("Error closing reader");
         exception.printStackTrace();
       }
     }
   }
   
   frame.setSize(250, 100);
   frame.setVisible(true);
 }

}



 </source>
   
  
 
  



JTextComponent: replaceSelection(String content)

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: select(int selectionStart, int selectionEnd)

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: setDocument(Document doc)

   <source lang="java">
 

import java.awt.GridLayout; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Main {

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

}


 </source>
   
  
 
  



JTextComponent: setDragEnabled(boolean b)

   <source lang="java">
 

import java.awt.Container; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JTextField; public class Main extends JFrame {

 public static void main(String[] args) {
   new Main().setVisible(true);
 }
 public Main() {
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextField field1 = new JTextField("Life"s a drag", 20);
   JTextField field2 = new JTextField("and then you drop", 20);
   field1.setDragEnabled(true);
   field2.setDragEnabled(true);
   Container content = getContentPane();
   content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
   content.add(field1);
   content.add(field2);
   pack();
 }

}


 </source>
   
  
 
  



JTextComponent: setFocusAccelerator(char aKey)

   <source lang="java">
 

import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.SwingConstants; public class Main {

 public static void main(String[] args) {
   JLabel l;
   JTextField t;
   JButton b;
   JFrame f = new JFrame("Text Accelerator");
   
   f.add(l = new JLabel("Name:", SwingConstants.RIGHT));
   l.setDisplayedMnemonic("n");
   f.add(l = new JLabel("House/Street:", SwingConstants.RIGHT));
   l.setDisplayedMnemonic("h");
   f.add(l = new JLabel("City:", SwingConstants.RIGHT));
   l.setDisplayedMnemonic("c");
   f.add(l = new JLabel("State/County:", SwingConstants.RIGHT));
   l.setDisplayedMnemonic("s");
   f.add(l = new JLabel("Zip/Post code:", SwingConstants.RIGHT));
   l.setDisplayedMnemonic("z");
   f.add(l = new JLabel("Telephone:", SwingConstants.RIGHT));
   l.setDisplayedMnemonic("t");
   f.add(b = new JButton("Clear"));
   b.setMnemonic("l");
   f.add(t = new JTextField(35));
   t.setFocusAccelerator("n");
   f.add(t = new JTextField(35));
   t.setFocusAccelerator("h");
   f.add(t = new JTextField(35));
   t.setFocusAccelerator("c");
   f.add(t = new JTextField(35));
   t.setFocusAccelerator("s");
   f.add(t = new JTextField(35));
   t.setFocusAccelerator("z");
   f.add(t = new JTextField(35));
   t.setFocusAccelerator("t");
   f.add(b = new JButton("OK"));
   b.setMnemonic("o");
   f.pack();
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



JTextComponent: setNavigationFilter(NavigationFilter filter)

   <source lang="java">
 

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 MainClass {

 public static void main(String args[]) throws Exception {
   final String START_STRING = "Start\n";
   final int START_STRING_LENGTH = START_STRING.length();
   JFrame frame = new JFrame("Navigation Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JTextArea textArea = new JTextArea(START_STRING);
   textArea.setCaretPosition(START_STRING_LENGTH);
   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) {
       if (dot < START_STRING_LENGTH) {
         fb.setDot(START_STRING_LENGTH, bias);
       } else {
         fb.setDot(dot, bias);
       }
     }
     public void moveDot(NavigationFilter.FilterBypass fb, int dot, Position.Bias bias) {
       if (dot < START_STRING_LENGTH) {
         fb.setDot(START_STRING_LENGTH, bias);
       } else {
         fb.setDot(dot, bias);
       }
     }
   };
   textArea.setNavigationFilter(filter);
   frame.setSize(250, 150);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



JTextComponent: setSelectedTextColor(Color c)

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: setSelectionColor(Color c)

   <source lang="java">
 

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

}


 </source>
   
  
 
  



JTextComponent: setSelectionEnd(int selectionEnd)

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.JTextComponent; public class Main {

 public static void main(String[] argv) {
   JTextComponent c = new JTextArea();
   c.setSelectionEnd(20);
 }

}


 </source>
   
  
 
  



JTextComponent: setSelectionStart(int selectionStart)

   <source lang="java">
 

import javax.swing.JTextArea; import javax.swing.text.JTextComponent; public class Main {

 public static void main(String[] argv) {
   JTextComponent c = new JTextArea();
   c.setSelectionStart(10);
 }

}


 </source>
   
  
 
  



JTextComponent: write(Writer out)

   <source lang="java">
 

import java.awt.BorderLayout; import java.io.FileWriter; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JTextField; 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);
   
   FileWriter writer = null;
   try {
     writer = new FileWriter("filename.txt");
     nameTextField.write(writer);
   } catch (IOException exception) {
     System.err.println("Save oops");
     exception.printStackTrace();
   } finally {
     if (writer != null) {
       try {
         writer.close();
       } catch (IOException exception) {
         System.err.println("Error closing writer");
         exception.printStackTrace();
       }
     }
   }
   
   frame.setSize(250, 100);
   frame.setVisible(true);
 }

}


 </source>