Exact length of a JTextField

Hi,
I have a program where I read integer value from the database & create a JTextField on the GUI side. Number of characters user should enters in the JTextField should be equal to the value I have got from the database & only JTextField with columns 10 should be displayed
e.g If I get integer value 10 , I create a JTextField & call setColumns(10);
here is my program:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class test extends javax.swing.JFrame
     public test(String title) throws Exception
          super(title);
          this.setLayout(new java.awt.FlowLayout());
          javax.swing.JTextField tf = new javax.swing.JTextField();
          tf.setDocument(new LimitDocument(2));
          tf.setMargin(new Insets(0,0,0,0));
          tf.setColumns(2);
          this.getContentPane().add(tf);
     public static void main(String[] args) throws Exception
          test t = new test("Test");
          t.setSize(new java.awt.Dimension(500,500));
          t.setVisible(true);
//Inner Class
class LimitDocument extends PlainDocument {
private int limit;
public LimitDocument(int limit) {
super();
setLimit(limit); // store the limit
public final int getLimit(){
return limit;
public void insertString(int offset, String s, AttributeSet attributeSet) throws BadLocationException {
if(offset < limit){ // if we haven't reached the limit, insert the string
super.insertString(offset,s,attributeSet);
} // otherwise, just lose the string
public final void setLimit(int newValue) {
this.limit = newValue;
after running this propgram , I found that even if user is able to enter only the number of characters specified , but still JTextField leaves some SPACE after number of characters entered
In above example , I have Limit number of characters to be entered to 2
but after entering 2 chars , it showd some SPACE in the end, I dont want to show this SPACE to the user.
Pleae guide me
Thanks in advance
NJP

In above example , I have Limit number of characters to be entered to 2
but after entering 2 chars , it showd some SPACE in the end, I dont want to show this SPACE to the user.
Type "mm" into the field and you'll see that the string fills the box. Naturally, with a proportional font, "ii" etc won't.
By the way, the logic in your LimitDocument is flawed: as an illustraction, paste a string in there - or type two characters, move the cursor left and carry on typing.

Similar Messages

  • How to change the length of a JTextField?

    Hello,
    I am trying to shorten the length of a JTextField with the following code :
    // up to this point, getColumns() returns a value of 35.
    jTextField1.setColumns(20);
    (jTextField1.getParent()).invalidate();
    (jTextField1.getParent()).validate();
    When I ran this code, it does not change the length of the text field at all.
    I wonder if I am writing my code correctly or is there a better/more correct
    way to do this?
    Thank you for your help.
    Akino.

    Packing a frame works:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ShortText implements ActionListener {
        JTextField txtF;
        JFrame frame;
        public ShortText() {
         frame = new JFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         txtF = new JTextField(30);
         JButton btn = new JButton("Shorten");
         btn.addActionListener(this);
         frame.add(txtF, BorderLayout.NORTH);
         frame.add(btn, BorderLayout.SOUTH);
         frame.pack();
         frame.setVisible(true);
        public static void main(String[] args) {
         new ShortText();
        public void actionPerformed(ActionEvent e) {
         System.out.println("Old Columns: " + txtF.getColumns());
         txtF.setColumns(20);
         frame.pack();
         System.out.println("New Columns: " + txtF.getColumns());
    }

  • How to export exact length with iMovie?

    I edited a video in iMovie to be exactly 5 minutes long. After sharing it, however, when I watch the video in quicktime, it is 5:04 long. I need to get rid of the extra 4 seconds, but I checked the exported version, and the extra seconds were not added to the beginning or end of the project, so it is not a question of trimming it. How do I export the movie so that it preserves the exact length of the project?

    Do you have a title or end credit that is haning over the beginning or end?

  • How to set the maximum length in a JTextField component.

    Hi This is a basic doubt. How can i set the maximum lenght in a JTextField.. I tried the setColumns() method. It doesnt do anything.. Pls Help.
    Thanks
    Rajeev

    Here's an example using PlainDocument.
    textField.setDocuemnt( new TextFieldVerifier() );
    class TextFieldVerifier extends PlainDocument {
    int requiredLength = 10; // whatever length you want
    public void insertString( int offset, String str, AttributeSet attSet ) throws BadLocationException {           
    boolean valid = true;          
    if (str == null) {
    return;
    String old = getText( 0, getLength() );
    /* insert the new string at the given offset, into the old string */     
    String newStr = old.substring( 0, offset ) + str + old.substring( offset );
    if (newStr.length() > requiredLength)
    valid = false;
    Toolkit.getDefaultToolkit().beep();
    if ( valid )
    super.insertString( offset, str, attSet );
    }

  • A problem about a string length of the JTextField.

    Hi, all.
    I have a problem of check the length of the text in the JTextField. Look at the following program snippet.
    import javax.swing.text.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.DocumentEvent;
    public class test extends JFrame
    JTextField jTextField1 = new JTextField(50);
    static final int MAX_LENGTH = 10;
    public static void main(String[] asArgs)
    test testFrm = new test();
    testFrm.setVisible(true);
    class newDocument extends PlainDocument
    public void insertString(int offs,String str,AttributeSet a) throws
    BadLocationException
    String strTmp;
    strTmp = jTextField1.getText();
    int nSize1 = strTmp.getBytes().length;
    int nSize2 = str.getBytes().length;
    if(nSize1 + nSize2 > MAX_LENGTH)
    return;
    else
    super.insertString(offs,str,a);
    public test() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    private void jbInit() throws Exception {
    jTextField1.setText("");
    this.getContentPane().add(jTextField1, BorderLayout.NORTH);
    newDocument myDocument = new newDocument();
    jTextField1.setDocument(myDocument);
    public void removeUpdate(DocumentEvent e)
    jTextField1.setText(sOldStr);
    System.out.println("removeUpdate");
    Attention please: I want to check the bytes of the inputted string. It is no problem with english string inputting, but if I input a string with other charset such as A Japanese string or a Chinese string, it doesn't work(when your input string is as long as the MAX_LENGTH, it doesn't work well). How can solve it? Thank you very much.

    i believe the problem is that you didn't set the font of the JTextField.
    I don't know what's the default Font of the JTextField is (i think it's dialog)
    the default textfield cannot display chinese character (and mort unicode character - latin 2 - extends and above).
    You need to set the font that can handle displaying the CHinese & Japanese characters (however, your application may not work if you port your app to another computer..and they don't have the font that you specified (unless you ship the font with it))
    // why are you getting converting the String to byte and then get the length???
    int nSize1 = jTextField1.getText( ).length();

  • How to i get the exact length of a playlist?

    i am have upgraded iTunes
    and AMONG the PLETHORA of un-needed and ANNOYING changes....
    is the fact the the LENGTH of a playlist is posted at 1.6 or 2.4 etc.
    i liked how it used to say 1hour 13 minutes
    can anyone help me switch this back?

    This is a change Apple have made you cannot revert it. To complain or express dissatisfaction here does not mean Apple read it this is a user to user forum. To let Apple know how you feel use the feedback link
    http://www.apple.com/feedback/itunesapp.html

  • Is it possible to change the length of a note in the score editor?

    I thought I saw somewhere that it was now possible to adjust the length of a note in the score editor graphically, i.e. by clicking on the note and somehow adjust its length directly to change it from 1/4 note to 1/8 (for example).
    I don't want to do this by going over to the "Length" dialog on the left because I hate having to switch from thinking in terms of music notation and then having to think (temporarily) in MIDI ticks per beat, etc.
    I must admit that I'm finding it extremely frustrating to simply enter music into Logic in a score....I thought this was supposed to be one of its strengths but it seems to be providing amazing capabilities at the expense of ease of use for beginners.

    dhjdhj wrote:
    I thought I saw somewhere that it was now possible to adjust the length of a note in the score editor graphically, i.e. by clicking on the note and somehow adjust its length directly to change it from 1/4 note to 1/8 (for example).
    greetings dh... are you into Key Commands? There are two which will help you do the above in a trice:
    • Nudge Region/Event Length Right by SMPTE Frame
    • Nudge Region/Event Length Left by SMPTE Frame
    I set mine to the simple letter o and n
    - I click on a note and press o repeatedly.. it grows and grows longer and longer
    – I click on a note and press n repeatedly.. it shrinks and shrinks shorter and shorter
    All by little increments
    If you keep a Piano Roll window open while you do this, you can see the length do this exactly
    man, it is VERY quick and handy for changing the length of notes
    It really helps to have a view of the midi Piano Roll to cross check the exact length and position of the notes.
    Check out the Key Commands:
    • Set Next Higher division
    • Set Next lower division
    These change the note value in the transport bar near the time signature. Your time signature may be 4/4 but the "grid" on which the notes are appear in the Piano Roll could be displayed in quarter, 8th or 16th notes. If you experiment with these commands, then you can match the note lengths easily to the grid display visually (with the above nudge length commands)
    Also - you may like to experiment with the following 3 KEY Key Commands:
    1 • Nudge Region/Event Position Right by Nudge Value
    2 • Nudge Region/Event Position Left by Nudge Value
    This will move your selected notes forward in time or back in time according to the
    value that is set in the Transport bar - say it is 16ths .. then each press of the key will move the notes a 16th
    or if the value is 8th notes, then each press of the key forward or backwards will move the selected notes forward or back by this amount
    ... amazingly useful when you are taking a whole phrase and pasting it somewhere else, or if say you started to write a phrase in the Score Editor and you started on the wrong beat.. then you just Nudge back and forth
    3 • Set Nudge Value to Division
    .. this will in a trice change change the Nudge Value to whatever Note division value is set in the Transport bar
    HTH and forgive me if I have given you too much information
    ..problem is I spent too much time in the Transport Bar in Los Angeles last year drinking with the iSchwartz and other Logic reprobrates... you should join us some time

  • Zero fill and max length VC7 Compile to WebDynpro not working

    Hi,
    i try to call Customer get list and set the attributes zero fill and max length to the input table form.
    But the user has to put in the exact length and zero filled.
    Any idea what to do
    Thanks
    Uwe

    Hi Uwe,
    if I understand your question you need something like an alpha conversion.
    You can use a formula, therefore is an textfunction called LPAD(text,len,pad).
    You can use it like this:
    LPAD(@yourtext, 18, "0")
    @yourtext contains the input, the length is 18 and filling values is 0 like a alpha conversion.
    Best Regards,
    Marcel

  • Fixed length of a field

    Hi Guru's,
    Can anyone help me about my program.?
    How can i get the exact length of a field so that when they are concatenated they have the same size of the field.
    Thank You in advance.
    Regards,
    dranel

    hi,
    To find out the field length of a data object, use the LENGTH addition:
    DESCRIBE FIELD <f> LENGTH <l> IN CHARACTER MODE | IN BYTE MODE.
    exp.
    DATA: text(8) TYPE c,
          len TYPE i.
    DESCRIBE FIELD text LENGTH len IN CHARACTER MODE.
    o/p:-
    Field LEN contains the value 8.
    regards
    Gaurav

  • Doubt in length function

    I am beginner in PL/SQL.The Following statement returns only 40 thugh the exact length is 91.
    SELECT
    length(1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950)
    FROM dual
    Also, I get the same result whenever the input number's length exceeds 40. It is working successfully if the input numbers length is below 40.
    I am using PL/SQL developer.
    Please suggest

    You need to use quotes when using character data in SQL:
    SQL> select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Prod
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for 32-bit Windows: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    SQL> SELECT
      2  length(1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950)
      3  FROM dual;
    LENGTH(1234567891011121314151617181920212223242526272829303132333435363738394041
                                                                                  40
    SQL> SELECT
      2  length('1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950')
      3  from dual;
    LENGTH('123456789101112131415161718192021222324252627282930313233343536373839404
                                                                                  91

  • Using JTextField as an array.

    Hi I would like some help with createing a JTextField array. I cant seem to find anything wrong with my code but it keeps giving me an Error.
    Error Message: java.lang.ArrayIndexOutOfBoundsException
    This is what my code looks like.
    //Declare Component
    JTextField Length[];
    for(int i = 0; i < 5; i++)
    Length[i] = new JTextField("", 5);
    c.gridx = i;
    c.gridy = 0;
    panMiddle.add(Length, c);
    Please let me know what im doing wrong.

    You seem to have several things in error. Here is one way to do this. It creates an array of 4 JTextFields. A frequent beginner's mistake is to initialize the array but to forget to initialize the individual items, something that must be done if the items are objects (i.e., are not primative types such as int).
    public class MyClass extends JPanel
        private JTextField[] textFieldArray = new JTextField[4]; //array declared and initialized
        public MyClass()
            for (int i = 0; i < textFieldArray.length; i++)
                textFieldArray[i] = new JTextField(12); //init each array item here
                panMiddle.add(textFieldArray); // add it to my form here.
    Message was edited by:
    petes1234

  • Getting  the char length

    Hello all!!
    I´m working with type C, and I wonder how can I get, in my program, the length of a variable or a parameter declarated like this:
    PARAMETER: chain(10).
    I know that its lenght is 10 (max) but I would like to know if there is a way in ABAP  to get it dynamically, I mean, in the program.
    Thank you very much.
    Reyes.

    use describe statement as follows.
    data: n type i.
    describe field chain length n.
    if you want exact length of the content in chain.
    then use strlen().
    regds,
    kiran

  • Setting specific length for a line

    I'm looking for a way to enter an exact length for a line. Also, exact dimensions for a rectangle.
    I'm assuming there's a 'Properties' window or something that has the shape's properties, but I'm not seeing anything. I've searched the help site, but not seeing anything there either.
    Any assistance would be greatly appreciated.
    doug

    Look for the little downturned arrow in the tool options bar for more options for the different shape tools.
    I don't know that you can set a fixed length for the Line Tool, but could use the rectangle tool for a fixed line length.

  • Selecting actual length of data

    i am selecting from a txt file, but say this particular field in the txt file is varchar2(30), but the actual length of the data can vary, how do i select the actual length of the data,instead of getting the data followed by spaces?

    Hi Justin,
    It more like this.
    I am using the utl_fle to retrive data from a txt file.
    So say the length in the txt field is 30 characted.
    I have retrieved it using the utl_file and put it in variable A.
    But the data in variable A does not have 30 characters, it may vary depending on the data in the txt file.
    So how can i retrive the exact length of the data from the txt file,
    eg of txt data(each field is 30 char long, but actual data length is only six
    123123 123123 123123
    But when i retriev from utl_file its comes out as
    123123xxxxxxx
    xxx denotes spaces, so how do i just retreive 123123.
    The exact length of the records is random.Hope this is clearer.

  • How to get the correct length...removing appended extra ascii characters

    I have a table fs_lg_partgroups, having the columns description,subgroupname.
    I have a query like this..
    select description,length(description) from fs_lg_partgroups where subgroupname='FORMULA226';
    Then i got the output as
    formula226 and the length is 42. Even though there are 10 characters only.
    I came to know that some ascii characters are appended to description values, so it is showing the length like this.
    But i don't know how to remove those ASCII characters from description column for all rows to get the exact length.
    Please can u help me..

    If you have used char data type then use varchar2 datatype instead of char datatype for description column.
    Learn about char and varchar2 datatypes here.
    http://download-east.oracle.com/docs/cd/B10501_01/server.920/a96524/c13datyp.htm#7223

Maybe you are looking for