classpath-patches
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[cp-patches] FYI: Prevent multiple lines in JTextField


From: Meskauskas Audrius
Subject: [cp-patches] FYI: Prevent multiple lines in JTextField
Date: Tue, 15 Nov 2005 11:27:30 +0100
User-agent: Mozilla Thunderbird 1.0.2 (Windows/20050317)

JTextField is always a single line component. In GNU Classpath, it is possible to make it multi line by setting or pasting the line with line feeds. While this is highly impressive, the Sun's implementation never does this, replacing the line feeds by spaces instead. The unwanted resizing of the component generally does not look well in the applications that do not expect this.

The simplest way to reach the identical behaviour is to override setText and replaceSelection, replacing (if present) line feeds and carriage returns by spaces.

2005-11-15  Audrius Meskauskas  <address@hidden>

* javax/swing/JTextField.java (setText, replaceSelection, filterString): New methods.

Index: javax/swing/JTextField.java
===================================================================
RCS file: /cvsroot/classpath/classpath/javax/swing/JTextField.java,v
retrieving revision 1.26
diff -u -r1.26 JTextField.java
--- javax/swing/JTextField.java 31 Oct 2005 16:22:51 -0000      1.26
+++ javax/swing/JTextField.java 15 Nov 2005 10:09:24 -0000
@@ -511,4 +511,45 @@
     // javax.swing.text.FieldView.
     return horizontalVisibility;
   }
+  
+  /**
+   * JTextField is a single line component. The method replaces the line
+   * feeds by spaces.
+   */
+  public void replaceSelection(String content)
+  {
+    super.replaceSelection(filterString(content));
+  }
+  
+  /**
+   * JTextField is a single line component. The method replaces the line
+   * feeds by spaces.
+   */
+  public void setText(String content)
+  {
+    super.setText(filterString(content));
+  }
+  
+  /**
+   * Replaces line feeds and carriage returns by spaces.
+   * 
+   * @param content
+   */
+  String filterString(String content)
+  {
+    if (content.indexOf('\n') >= 0 || content.indexOf('\r') >= 0)
+      {
+        StringBuilder b = new StringBuilder(content);
+        char c;
+        for (int i = 0; i < b.length(); i++)
+          {
+            c = b.charAt(i);
+            if (c == '\n' || c == '\r')
+              b.setCharAt(i, ' ');
+          }
+        return b.toString();
+      }
+    else
+      return content;
+  }
 }

reply via email to

[Prev in Thread] Current Thread [Next in Thread]