JTextField.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /* JTextField.java --
  2. Copyright (C) 2002, 2004, 2005, 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package javax.swing;
  32. import java.awt.Dimension;
  33. import java.awt.Font;
  34. import java.awt.FontMetrics;
  35. import java.awt.Insets;
  36. import java.awt.Rectangle;
  37. import java.awt.event.ActionEvent;
  38. import java.awt.event.ActionListener;
  39. import java.beans.PropertyChangeEvent;
  40. import java.beans.PropertyChangeListener;
  41. import javax.accessibility.AccessibleContext;
  42. import javax.accessibility.AccessibleStateSet;
  43. import javax.swing.text.Document;
  44. import javax.swing.text.JTextComponent;
  45. import javax.swing.text.PlainDocument;
  46. import javax.swing.text.TextAction;
  47. public class JTextField extends JTextComponent
  48. implements SwingConstants
  49. {
  50. /**
  51. * AccessibleJTextField
  52. */
  53. protected class AccessibleJTextField extends AccessibleJTextComponent
  54. {
  55. private static final long serialVersionUID = 8255147276740453036L;
  56. /**
  57. * Constructor AccessibleJTextField
  58. */
  59. protected AccessibleJTextField()
  60. {
  61. super();
  62. }
  63. /**
  64. * Returns the accessible state of this <code>AccessibleJTextField</code>.
  65. *
  66. * @return the accessible state of this <code>AccessibleJTextField</code>
  67. */
  68. public AccessibleStateSet getAccessibleStateSet()
  69. {
  70. AccessibleStateSet state = super.getAccessibleStateSet();
  71. // TODO: Figure out what state must be added here to the super's state.
  72. return state;
  73. }
  74. }
  75. private static final long serialVersionUID = 353853209832607592L;
  76. private static final Action[] actions;
  77. /**
  78. * Name of the action that gets sent when the content of the text field
  79. * gets accepted.
  80. */
  81. public static final String notifyAction = "notify-field-accept";
  82. static
  83. {
  84. actions = new Action[1];
  85. actions[0] = new TextAction(notifyAction)
  86. {
  87. public void actionPerformed(ActionEvent event)
  88. {
  89. JTextField textField = (JTextField) event.getSource();
  90. textField.fireActionPerformed();
  91. }
  92. };
  93. }
  94. private int columns;
  95. private int align;
  96. /** @since 1.3 */
  97. private Action action;
  98. /** @since 1.3 */
  99. private String actionCommand;
  100. private PropertyChangeListener actionPropertyChangeListener;
  101. /**
  102. * The horizontal visibility of the textfield.
  103. */
  104. private BoundedRangeModel horizontalVisibility;
  105. /**
  106. * Creates a new instance of <code>JTextField</code>.
  107. */
  108. public JTextField()
  109. {
  110. this(null, null, 0);
  111. }
  112. /**
  113. * Creates a new instance of <code>JTextField</code>.
  114. *
  115. * @param text the initial text
  116. */
  117. public JTextField(String text)
  118. {
  119. this(null, text, 0);
  120. }
  121. /**
  122. * Creates a new instance of <code>JTextField</code>.
  123. *
  124. * @param columns the number of columns
  125. *
  126. * @exception IllegalArgumentException if columns %lt; 0
  127. */
  128. public JTextField(int columns)
  129. {
  130. this(null, null, columns);
  131. }
  132. /**
  133. * Creates a new instance of <code>JTextField</code>.
  134. *
  135. * @param text the initial text
  136. * @param columns the number of columns
  137. *
  138. * @exception IllegalArgumentException if columns %lt; 0
  139. */
  140. public JTextField(String text, int columns)
  141. {
  142. this(null, text, columns);
  143. }
  144. /**
  145. * Creates a new instance of <code>JTextField</code>.
  146. *
  147. * @param doc the document to use
  148. * @param text the initial text
  149. * @param columns the number of columns
  150. *
  151. * @exception IllegalArgumentException if columns %lt; 0
  152. */
  153. public JTextField(Document doc, String text, int columns)
  154. {
  155. if (columns < 0)
  156. throw new IllegalArgumentException();
  157. this.columns = columns;
  158. // Initialize the horizontal visibility model.
  159. horizontalVisibility = new DefaultBoundedRangeModel();
  160. setDocument(doc == null ? createDefaultModel() : doc);
  161. if (text != null)
  162. setText(text);
  163. // default value for alignment
  164. align = LEADING;
  165. }
  166. /**
  167. * Creates the default model for this text field.
  168. * This implementation returns an instance of <code>PlainDocument</code>.
  169. *
  170. * @return a new instance of the default model
  171. */
  172. protected Document createDefaultModel()
  173. {
  174. return new PlainDocument();
  175. }
  176. /**
  177. * Sets the document to be used for this JTextField.
  178. *
  179. * This sets the document property <code>filterNewlines</code> to
  180. * <code>true</code> and then calls the super behaviour to setup a view and
  181. * revalidate the text field.
  182. *
  183. * @param doc the document to set
  184. */
  185. public void setDocument(Document doc)
  186. {
  187. doc.putProperty("filterNewlines", Boolean.TRUE);
  188. super.setDocument(doc);
  189. }
  190. /**
  191. * Returns the class ID for the UI.
  192. *
  193. * @return "TextFieldUI";
  194. */
  195. public String getUIClassID()
  196. {
  197. return "TextFieldUI";
  198. }
  199. /**
  200. * Adds a new listener object to this text field.
  201. *
  202. * @param listener the listener to add
  203. */
  204. public void addActionListener(ActionListener listener)
  205. {
  206. listenerList.add(ActionListener.class, listener);
  207. }
  208. /**
  209. * Removes a listener object from this text field.
  210. *
  211. * @param listener the listener to remove
  212. */
  213. public void removeActionListener(ActionListener listener)
  214. {
  215. listenerList.remove(ActionListener.class, listener);
  216. }
  217. /**
  218. * Returns all registered <code>ActionListener</code> objects.
  219. *
  220. * @return an array of listeners
  221. *
  222. * @since 1.4
  223. */
  224. public ActionListener[] getActionListeners()
  225. {
  226. return (ActionListener[]) getListeners(ActionListener.class);
  227. }
  228. /**
  229. * Sends an action event to all registered
  230. * <code>ActionListener</code> objects.
  231. */
  232. protected void fireActionPerformed()
  233. {
  234. ActionEvent event = new ActionEvent(this, 0,
  235. actionCommand == null ? getText() : actionCommand);
  236. ActionListener[] listeners = getActionListeners();
  237. for (int index = 0; index < listeners.length; ++index)
  238. listeners[index].actionPerformed(event);
  239. }
  240. /**
  241. * Returns the number of columns of this text field.
  242. *
  243. * @return the number of columns
  244. */
  245. public int getColumns()
  246. {
  247. return columns;
  248. }
  249. /**
  250. * Sets the number of columns and then invalidates the layout.
  251. * @param columns the number of columns
  252. * @throws IllegalArgumentException if columns < 0
  253. */
  254. public void setColumns(int columns)
  255. {
  256. if (columns < 0)
  257. throw new IllegalArgumentException();
  258. this.columns = columns;
  259. invalidate();
  260. //FIXME: do we need this repaint call?
  261. repaint();
  262. }
  263. /**
  264. * Returns the horizontal alignment, which is one of: JTextField.LEFT,
  265. * JTextField.CENTER, JTextField.RIGHT, JTextField.LEADING,
  266. * JTextField.TRAILING.
  267. * @return the horizontal alignment
  268. */
  269. public int getHorizontalAlignment()
  270. {
  271. return align;
  272. }
  273. /**
  274. * Sets the horizontal alignment of the text. Calls invalidate and repaint
  275. * and fires a property change event.
  276. * @param newAlign must be one of: JTextField.LEFT, JTextField.CENTER,
  277. * JTextField.RIGHT, JTextField.LEADING, JTextField.TRAILING.
  278. * @throws IllegalArgumentException if newAlign is not one of the above.
  279. */
  280. public void setHorizontalAlignment(int newAlign)
  281. {
  282. //FIXME: should throw an IllegalArgumentException if newAlign is invalid
  283. if (align == newAlign)
  284. return;
  285. int oldAlign = align;
  286. align = newAlign;
  287. firePropertyChange("horizontalAlignment", oldAlign, newAlign);
  288. invalidate();
  289. repaint();
  290. }
  291. /**
  292. * Sets the current font and revalidates so the font will take effect.
  293. */
  294. public void setFont(Font newFont)
  295. {
  296. super.setFont(newFont);
  297. revalidate();
  298. }
  299. /**
  300. * Returns the preferred size. If there is a non-zero number of columns,
  301. * this is the number of columns multiplied by the column width, otherwise
  302. * it returns super.getPreferredSize().
  303. */
  304. public Dimension getPreferredSize()
  305. {
  306. Dimension size = super.getPreferredSize();
  307. if (columns != 0)
  308. {
  309. Insets i = getInsets();
  310. size.width = columns * getColumnWidth() + i.left + i.right;
  311. }
  312. return size;
  313. }
  314. /**
  315. * Returns the scroll offset in pixels.
  316. *
  317. * @return the scroll offset
  318. */
  319. public int getScrollOffset()
  320. {
  321. return horizontalVisibility.getValue();
  322. }
  323. /**
  324. * Sets the scroll offset in pixels.
  325. *
  326. * @param offset the scroll offset
  327. */
  328. public void setScrollOffset(int offset)
  329. {
  330. // Automatically sets to the highest possible value if
  331. // offset is bigger than that.
  332. horizontalVisibility.setValue(
  333. Math.min(horizontalVisibility.getMaximum()
  334. - horizontalVisibility.getExtent(),
  335. offset));
  336. }
  337. /**
  338. * Returns the set of Actions that are commands for the editor.
  339. * This is the actions supported by this editor plus the actions
  340. * of the UI (returned by JTextComponent.getActions()).
  341. */
  342. public Action[] getActions()
  343. {
  344. return TextAction.augmentList(super.getActions(), actions);
  345. }
  346. public void postActionEvent()
  347. {
  348. String command = actionCommand != null ? actionCommand : getText();
  349. ActionEvent event = new ActionEvent(this, 0, command);
  350. ActionListener[] listeners = getActionListeners();
  351. for (int index = 0; index < listeners.length; ++index)
  352. listeners[index].actionPerformed(event);
  353. }
  354. /**
  355. * @since 1.3
  356. */
  357. public Action getAction()
  358. {
  359. return action;
  360. }
  361. /**
  362. * @since 1.3
  363. */
  364. public void setAction(Action newAction)
  365. {
  366. if (action == newAction)
  367. return;
  368. if (action != null)
  369. {
  370. removeActionListener(action);
  371. action.removePropertyChangeListener(actionPropertyChangeListener);
  372. actionPropertyChangeListener = null;
  373. }
  374. Action oldAction = action;
  375. action = newAction;
  376. if (action != null)
  377. {
  378. addActionListener(action);
  379. actionPropertyChangeListener = createActionPropertyChangeListener(action);
  380. action.addPropertyChangeListener(actionPropertyChangeListener);
  381. }
  382. //FIXME: is this a hack? The horizontal alignment hasn't changed
  383. firePropertyChange("horizontalAlignment", oldAction, newAction);
  384. }
  385. /**
  386. * Sets the command string used in action events.
  387. * @since 1.3
  388. */
  389. public void setActionCommand(String command)
  390. {
  391. actionCommand = command;
  392. }
  393. /**
  394. * @since 1.3
  395. */
  396. protected PropertyChangeListener createActionPropertyChangeListener(Action action)
  397. {
  398. return new PropertyChangeListener()
  399. {
  400. public void propertyChange(PropertyChangeEvent event)
  401. {
  402. // Update properties "action" and "horizontalAlignment".
  403. String name = event.getPropertyName();
  404. if (name.equals("enabled"))
  405. {
  406. boolean enabled = ((Boolean) event.getNewValue()).booleanValue();
  407. JTextField.this.setEnabled(enabled);
  408. }
  409. else if (name.equals(Action.SHORT_DESCRIPTION))
  410. {
  411. JTextField.this.setToolTipText((String) event.getNewValue());
  412. }
  413. }
  414. };
  415. }
  416. /**
  417. *
  418. * @since 1.3
  419. */
  420. protected void configurePropertiesFromAction(Action action)
  421. {
  422. if (action != null)
  423. {
  424. setEnabled(action.isEnabled());
  425. setToolTipText((String) action.getValue(Action.SHORT_DESCRIPTION));
  426. }
  427. else
  428. {
  429. setEnabled(true);
  430. setToolTipText(null);
  431. }
  432. }
  433. /**
  434. * Returns the column width, which is the width of the character m
  435. * for the font in use.
  436. * @return the width of the character m for the font in use.
  437. */
  438. protected int getColumnWidth()
  439. {
  440. FontMetrics metrics = getToolkit().getFontMetrics(getFont());
  441. return metrics.charWidth('m');
  442. }
  443. /**
  444. * Returns the accessible context associated with the <code>JTextField</code>.
  445. *
  446. * @return the accessible context associated with the <code>JTextField</code>
  447. */
  448. public AccessibleContext getAccessibleContext()
  449. {
  450. if (accessibleContext == null)
  451. accessibleContext = new AccessibleJTextField();
  452. return accessibleContext;
  453. }
  454. /**
  455. * Returns the bounded range model that describes the horizontal visibility
  456. * of the text field in the case when the text does not fit into the
  457. * available space. The actual values of this model are managed by the look
  458. * and feel implementation.
  459. *
  460. * @return the bounded range model that describes the horizontal visibility
  461. */
  462. public BoundedRangeModel getHorizontalVisibility()
  463. {
  464. return horizontalVisibility;
  465. }
  466. /**
  467. * Returns <code>true</code>, unless this is embedded in a
  468. * <code>JViewport</code> in which case the viewport takes responsibility of
  469. * validating.
  470. *
  471. * @return <code>true</code>, unless this is embedded in a
  472. * <code>JViewport</code> in which case the viewport takes
  473. * responsibility of validating
  474. */
  475. public boolean isValidateRoot()
  476. {
  477. return ! (getParent() instanceof JViewport);
  478. }
  479. public void scrollRectToVisible(Rectangle r)
  480. {
  481. int v = horizontalVisibility.getValue();
  482. // The extent value is the inner width of the text field.
  483. int e = horizontalVisibility.getExtent();
  484. Insets i = getInsets();
  485. // The x value in the rectangle (usually) denotes the new location
  486. // of the caret. We check whether the location lies inside the left or
  487. // right border and scroll into the appropriate direction.
  488. // The calculation has to be shifted by the BoundedRangeModel's value
  489. // because that value was already used to calculate r.x (this happens
  490. // as part of a modelToView() call in FieldView).
  491. if (r.x < i.left)
  492. setScrollOffset(v + r.x - i.left);
  493. else if (r.x > e + i.left)
  494. setScrollOffset(r.x + v - e - i.left);
  495. }
  496. }