How to make jTextField 's input unscrollable?

Dear All
i create a JTextField, i want to set it inputsize = 5(charaters)
i am doing like this
JTextField jTextField = new JTextField(5);
jTextField.setScrollOffset(0);
but it doesnot work out
it is still scrollable, i main i could input more than
5 charaters
How to fix JTextField's input size?
Thx in advance

Hi,
that does not change the amount of characters, you can input, it only says, that the JTextFields-size should be 5 times as wide as an average char.
If you want to limit the characters you will have to replace the Plaindocument JTextFields uses internally with a subclass of it, that overwrites its insertString(...)-method. An example, that makes all input upcase is found in the documentation of JTextField. You can do your checking in a similar way there - just checking if the length of the string to insert plus the length of the text that is currently in the box is greater than the maximum length - if it is not, pass all parameter simply to the super.insertString(...)-method - if it is greater, that only do a Toolkit.getDefaultToolkit().beep().
Also there are many topics dealing with this stuff - please search the forum for it.
greetings Marsian

Similar Messages

  • How to Make JTextField Accept Only Specific Numbers?

    Hello There
    I've made 3 JTexfields That accepts only Numbers
    But I Want To Make Them Accpets Numbers only from 1 to 12
    and if the number is greater than 12 they don't accept it?
    another Thing That I've Set Their Columns To 2 meaning that i want the user to enter only two numbers
    but yet the user can enter many numbers how would i restrict entering numbers to only two numbers?
    here's my code:
      import java.awt.*;
      import javax.swing.*;
      import javax.swing.text.*;
      public class ManyText extends JFrame{
           public static void main(String[]args){
           JTextField[ ] text = new JTextField[3];
           JButton button=new JButton("Press");
        for(int i = 0; i < text.length; i++)
         text[i] = new JTextField(3);
         for(int i = 0; i < text.length; i++){
         text.setColumns(2);     
    text[i].setDocument(new PlainDocument(){
    public void insertString(int offs, String str,
    AttributeSet a) throws BadLocationException{
    if("0123456789".indexOf(str) < 0)
    java.awt.Toolkit.getDefaultToolkit().beep();
    return;
    super.insertString(offs, str, a);
         JFrame f=new JFrame();
         f.setSize(200,200);
         f.setLayout(new FlowLayout());
         f.add(text[0]);
    f.add(text[1]);
    f.add(text[2]);     
         f.setVisible(true);     

    ejp wrote:
    Actually I would suggest you're using the wrong control. I would use a JComboBox or a JSpinner for this.I suggested he use a JSpinner 1-2 threads ago. Maybe if he hears it enough, he'll believe it.

  • How to make dialogbox to input username and passwd

    Hello,
    I want to make GU interface to allow users to input their username and password, does anybody give me sample code, thanks a lot.
    Grace

    C'mon man. RTFM.
    Check out the tutorials on the left to figure out how to create frames and dialogs using the AWT and with Swing

  • How to make sure the input is an Integer?

    The code is like this:
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.io.*;
    public class addPanel extends JPanel implements ActionListener {
         private JLabel lblName, lblStreetNum, lblStreetName, lblSuburb, lblPostcode, lblTele, lblEmail, lblPackage;
         private JButton btnAdd, btnClear;
         private JButton btnLoad;
         private JScrollPane scroll;
         private JRadioButton rbtnBasic, rbtnMovie, rbtnPlus;
         private JTextField txtName, txtStreetNum, txtStreetName, txtSuburb, txtTele, txtEmail, txtPostcode;
         private JTextArea display;
    * Create a new <code>addPanel</code>.
    * Here goes the design and implementation of the search panel.
    * The user can enter all the fields that specific the subscriber's information.
         public addPanel() {
              setLayout(new BorderLayout());
              JPanel all = new JPanel(new FlowLayout());
              lblName = new JLabel("Name:");
              lblName.setPreferredSize(new java.awt.Dimension(100, 20));
              lblStreetNum = new JLabel("Street Number:");
              lblStreetNum.setPreferredSize(new java.awt.Dimension(100, 20));
              lblStreetName = new JLabel("Street Name:");
              lblStreetName.setPreferredSize(new java.awt.Dimension(100, 20));
              lblSuburb = new JLabel("Suburb:");
              lblSuburb.setPreferredSize(new java.awt.Dimension(100, 20));
              lblPostcode = new JLabel("Postcode:");
              lblPostcode.setPreferredSize(new java.awt.Dimension(100, 20));
              lblTele = new JLabel("Telephone:");
              lblTele.setPreferredSize(new java.awt.Dimension(100, 20));
              lblEmail = new JLabel("Email:");
              lblEmail.setPreferredSize(new java.awt.Dimension(100, 20));
              lblPackage = new JLabel("Package:");
              lblPackage.setPreferredSize(new java.awt.Dimension(100, 20));
              txtName = new JTextField("");
              txtName.setPreferredSize(new java.awt.Dimension(300, 25));
              txtStreetNum = new JTextField("");
              txtStreetNum.setPreferredSize(new java.awt.Dimension(300, 25));
              txtStreetName = new JTextField("");
              txtStreetName.setPreferredSize(new java.awt.Dimension(300, 25));
              txtSuburb = new JTextField("");
              txtSuburb.setPreferredSize(new java.awt.Dimension(300, 25));
              txtPostcode = new JTextField("");
              txtPostcode.setPreferredSize(new java.awt.Dimension(300, 25));
              txtTele = new JTextField("");
              txtTele.setPreferredSize(new java.awt.Dimension(300, 25));
              txtEmail = new JTextField("");
              txtEmail.setPreferredSize(new java.awt.Dimension(300, 25));
              btnAdd = new JButton("Add");
              btnAdd.setPreferredSize(new java.awt.Dimension(90, 25));
              btnClear = new JButton("Clear");
              btnClear.setPreferredSize(new java.awt.Dimension(90, 25));
              btnLoad = new JButton("Load");
              btnLoad.setPreferredSize(new java.awt.Dimension(90, 25));
              btnLoad.addActionListener(this);
              btnAdd.addActionListener(this);
              btnClear.addActionListener(this);
              rbtnBasic = new JRadioButton("Basic");
              rbtnBasic.setSelected(true);
              rbtnMovie = new JRadioButton("Movie Essentials");
              rbtnPlus = new JRadioButton("Entertainment Plus");
              ButtonGroup group = new ButtonGroup();
              group.add(rbtnBasic);
              group.add(rbtnMovie);
              group.add(rbtnPlus);
              JPanel rbtnPanel = new JPanel (new GridLayout(3,1));
              rbtnPanel.setPreferredSize(new java.awt.Dimension(300, 90));
              rbtnPanel.add(rbtnBasic); rbtnPanel.add(rbtnMovie); rbtnPanel.add(rbtnPlus);
              display = new JTextArea( 100, 130);
              display.setPreferredSize(new java.awt.Dimension(350, 200));
              scroll = new JScrollPane();
              scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
              scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              scroll.setPreferredSize(new java.awt.Dimension(350, 200));
              scroll.getViewport().add(display);
              all.add(lblName); all.add(txtName);
              all.add(lblStreetNum); all.add(txtStreetNum);
              all.add(lblStreetName); all.add(txtStreetName);
              all.add(lblSuburb); all.add(txtSuburb);
              all.add(lblPostcode); all.add(txtPostcode);
              all.add(lblTele); all.add(txtTele);
              all.add(lblEmail); all.add(txtEmail);
              all.add(lblPackage); all.add(rbtnPanel);
              all.add(btnAdd); all.add(btnClear);
              all.add(scroll);
              add(all);
         public void actionPerformed (ActionEvent e) {
              String ac = e.getActionCommand();
              String testStNum = txtStNum.getText();
              String testPostcode = txtPostcode.getText();
              String testTele = txtTele.getText();
              String packageType = "";
              if (rbtnBasic.isSelected()) { packageType = "Basic";}
              else if (rbtnMovie.isSelected()) { packageType = "Movie Essentials";}
              else if (rbtnPlus.isSelected()) { packageType = "Entertainment Plus";}
              // if "add" button is pressed
              if (ac.equals("Add")) {
    //               int stNum = Integer.parseInt(testStNum);
    //               int tele = Integer.parseInt(testStNum);
    //               int postcode = Integer.parseInt(testStNum);
                   // check the user has enter the fields or not
                   if ( (txtName.getText().equals("")) ||
                   (txtStreetNum.getText().equals("")) ||
                   (txtStreetName.getText().equals("")) ||
                   (txtSuburb.getText().equals("")) ||
    (txtPostcode.getText().equals("")) ||
    (txtTele.getText().equals("")) ||
    (txtEmail.getText().equals("")) ) {
                        display.append("Please fill in the fields in order to add a Subscriber!\n\n");
                   else {
                        session.addSubscriber(txtName.getText() , txtStreetNum.getText(), txtStreetName.getText(), txtSuburb.getText(), txtPostcode.getText(), txtTele.getText(), txtEmail.getText(), packageType);
                        display.append("Subscriber successfully added!\n\n");
                        txtName.setText(""); txtStreetNum.setText("");
                        txtStreetName.setText(""); txtSuburb.setText("");
                        txtTele.setText(""); txtEmail.setText(""); txtPostcode.setText("");
              if (ac.equals("Clear")) {
                   txtName.setText(""); txtStreetNum.setText("");
                   txtStreetName.setText(""); txtSuburb.setText("");
                   txtTele.setText(""); txtEmail.setText(""); txtPostcode.setText("");
                   display.setText("");
    This is kinda stupid actually,
    I want the input of txtStNum, txtPostcode, and txtTele must be Integer.
    If they are not Integer, the session.addSubscriber() will not be called,
    and in the TextArea --> display tell the user to input Integer......
    Thanks..

    Ok, that was difficult to read because you didnt use [ code ] tags... however... maybe this is something you could use with a keylistener for your text boxes
        public static void checkIsNumber(java.awt.event.KeyEvent evt){
            char c = evt.getKeyChar();
            //checks to see if the Key hit is a digit or backspace or delete
            if (!((Character.isDigit(c) ||
            (c == java.awt.event.KeyEvent.VK_BACK_SPACE) ||
            (c == java.awt.event.KeyEvent.VK_DELETE) ||
            (c == java.awt.event.KeyEvent.VK_MINUS)))) {
                //If not then beep and consume the event.
                Toolkit.getDefaultToolkit().beep();
                evt.consume();
        }If you don't want negitive numbers then take out the VK_MINUS portion of the if.
    This thing goes in your keyTyped event, if the input from the key is incorrect the program beeps at you and does nothing. you could easily change it to fit whatever needs you may have (such as displaying the error)

  • How can make JTextField display all ASCII character?

    I am writing a java app. There is a Jtextfield . I need display some special character in this jtextfield such as ASCII code is 135(&#135), 164(&#164), 167(&#167) and so on. Thees characters whose ASCII code is 164, 167 can correctly display in spite of you set any font to this jtextfield. But the character whose ASCII code is 135 can`t correctly display. It display as a [];. Who knows and has some ideas?
    Thx. Bob

    Thx any way.
    Now I found a another way to display the (char)135(display as "�").
    First, i defined a static attribute :
    public final static String ASCII_CODE_IS_135 = "�";
    Then, When I need display the char, I display the static attribute value. I found the textfield almost can display all special character by this way in spite of using what font.
    Thx again.

  • Help:How to make static text in JTextField??

    How to make a text to be displayed initially on a JTextField, yet we can not change the text (so the text
    is static)?
    The other question:
    How to make an input mask so that a JTextField
    has input pattern of XXX.XXX.XXX.XXX
    (which is the mask of IP Address) ??
    What I know that limiting input in JTextField can be done
    by extending PlainDocument....what about the cases above??
    Please reply if you know.
    Thanks a lot,
    Ted.

    For the first question, just call setEditable(false).

  • How do you make JTextFields Update?

    Ok, im just starting out learning about swing and so forth.. and im making this simple calculator type program.. but, i have no idea how to make the 'answer' part update when i hit the equals button...
    At the moment, i have an action Listener assigned to the button, and when i click it, the string that the answer originally showed does change to what i want it to be, but hte screen itself doesn't update to show it...
    heres the code so far:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.math.*;
    public class Calculator extends JFrame{
         private JTextField input1, input2, output;
         private JComboBox list;
         private JButton equals;
         private BigDecimal big1;
         private BigDecimal big2;
         private String s = "bob";
         private String math[] = {" +", " -", " /", " *"};
         public Calculator(){
         super("Calculator for big Numbers");
         Container c = getContentPane();
         c.setLayout(new FlowLayout());
         input1 = new JTextField(20);
         input2 = new JTextField(20);
         output = new JTextField(s, 40);
         output.setEditable(false);
         list = new JComboBox(math);
         list.setMaximumRowCount(4);
         equals = new JButton("=");
         c.add(input1);
         c.add(list);
         c.add(input2);
         c.add(equals);
         c.add(output);
         CalculatorHandler handler = new CalculatorHandler();
         input1.addActionListener(handler);
         input2.addActionListener(handler);
         equals.addActionListener(handler);
         output.addActionListener(handler);
         setSize(750, 100);
         show();
         public static void main(String arg[]){
         Calculator cal = new Calculator();
         cal.addWindowListener(
                   new WindowAdapter(){
                        public void windowClosing(WindowEvent e){
                        System.exit(0);
         private class CalculatorHandler implements ActionListener{
              public void actionPerformed(ActionEvent e){
              if(e.getSource() == input1)
                   big1 = new BigDecimal(e.getActionCommand());
              if(e.getSource() == input2)
                   big2 = new BigDecimal(e.getActionCommand());
              if(e.getSource() == equals){
                   s = "" + big1.add(big2);
                   System.out.println(s);
    }Also.. at the moment, the addition only occurs if you hit enter after putting the number in the text boxes.. if you just enter a number, and then click on to the next box, you get an error.. is there any way around this?
    Thanks

    the state of your system is the problem here
    when return is pressed on the textfield, the actionlistener parses the BigDecimal, but when the calculate is pressed it expects the fields to be there
    you need to manage the state better. The calculate button cannot work unless the fields are present. Add a method to parse a textfield, if no text is present, create a zero. You could also activate the button only after valid input is given (most components in swing have a setEnabled(boolean) method)

  • How to make numbers in message text input  fields left aligned?

    Hi Friends
    I have completed one of my task .but getting result right side of the field.
    how to make numbers in message text input  fields left aligned?
    Thanks
    Aravinda

    Hi ,
    Sorry for late replay i am trying this alos not set that page....
    pageContext.forwardImmediatelyToCurrentPage(null, true, null);
    and one more that kff field working is fine for ex display any text pled displayed properly and only problem is not set the value and HrSitKeyFlex6 and HrSitKeyFlex7 fields are perfectly get the values but not pront HrSitKeyFlex8 that only my issue....
    Regards,
    Srini

  • How to make a Input Field with multiple lines?

    hey folks,
    i need to make a popup window or a dynpro with 2 input fields, where the user can write on multiple lines. why isnt there such an input field in the screen painter? how can i make this? if i can do this with a dynpro it would be nice but a popup with that feature would be better. didnt found any infos anywhere except for that thread, but its answer didnt work with my dynpro:
    How to make a input/output field with multiple lines
    thx for any helping answer

    i made it just like in that thread but there is an error message telling that gv_custom_container is not declared.
    *  MODULE status_0110 OUTPUT
    MODULE status_0110 OUTPUT.
      CREATE OBJECT custom_container
        EXPORTING
          container_name              = 'TEXT_CONTROL'
        EXCEPTIONS
          cntl_error                  = 1
          cntl_system_error           = 2
          create_error                = 3
          lifetime_error              = 4
          lifetime_dynpro_dynpro_link = 5.
      CREATE OBJECT text_editor
        EXPORTING
          parent                     = gv_custom_container
          wordwrap_mode              = cl_gui_textedit=>wordwrap_at_windowborder
          wordwrap_to_linebreak_mode = cl_gui_textedit=>false
        EXCEPTIONS
          error_cntl_create          = 1
          error_cntl_init            = 2
          error_cntl_link            = 3
          error_dp_create            = 4
          gui_type_not_supported     = 5.
      SET PF-STATUS 'STATUS_0110'.
      SET TITLEBAR 'TITLE'.
    ENDMODULE.                    "status_0110 OUTPUT
    Edited by: rafe b. on Oct 26, 2009 2:56 PM

  • How to make a form for input in web interface builder

    Hi expert:
        How to make a form for input in web interface builder?I have already used it to do PS planning, but I don't know how to  draw lines and checkboxes . Thanks in advance.
    Allen

    WAD:
    Open the WAD and create a new template. On the left hand navigation you will have several Web Items available. Under 'Standard' you have 'Analysis' item. Pull that into your template to the right. Under the Properties tab you need to pick the query [form/layout] that you have built in Query Designer.
    You will also find other items such as Button group, Checkbox, drop down, list box etc available. Pick and drag into the template whatever it is you require. Lets say you want a button. Under the Properties tab select the 'Command' that you require. You could use standard commands that are available there. You could also define functions and commands that you require.
    Query Designer:
    Open the QD and drag the characteristics and key figures that you require into the rows and columns of the QD. You would need to specify restrictions under the Filter tab of the QD based on the granularity of data that you require. You would need to remember that the key figures need to be made Input Ready [do this by clicking on KF and on the planning tab select "change by user and planning functions"].
    This shouldgive you a start. After you've explored it yourself a bit we can discuss further and I can certainly provide you additional details/material on these areas.
    Srikant

  • How to make hyperlinks in JTextField/JtextArea  ??

    My JTextField/JtextArea has got this Text.
    String text = "Get information from http://www.hotmail.com, if you have problems go to http://www.google.com " ;
    How to make hyperlinks for http://www.hotmail.com and http://www.google.com texts only???
    And how to call those sites???

    Add a mouse listener, when the user double clicks - see if they've clicked on text that is a valid link.
    The limitation of using textfield or textarea is that you get no styling. I dont know why you're refusing those suggestions, but you're just creating more work for yourself.

  • How to make the inputs appear in Playback

    Hi,
    I would like to know how to make the inputs (line-in, mic, SPDIF-in) appear in playback of windows's mixer ?
    Im running XP pro sp3 with XFI Extreme Audio PCI-Express.
    I dont know why but there is no inputs in playback that making me unable to hear it while its being recorded.
    <img border="0" height="405" width="640" src="http://img70.imageshack.us/img70/672/mixergq0.png">
    <img border="0" height="542" width="640" src="http://img399.imageshack.us/img399/486/allmysettingsmq2.png">
    Message Edited by Nuja on 0-06-2009 2:07 [email protected]

    - I've read a little more and come to these conclusions:
    . The instructions presume that a CD is included with the card for the purpose of installing the software. A CD/DVD reader is a requirement for this reason.
    2. The card uses Intel HD Audio. This changes enough of what I know about CL's card that I really don't know that the lack of external inputs in the playback mixer is not intentional and uni'versal. A recording application could let you listen to what is being recorded by having an option of playing back what's being recorded.
    I have enough uncertainty now that I don't think it's useful for me to continue commenting. If someone who has a? PCI Express X-Fi Xtreme Audio that came with the software CD and hard-copy documentation wishes to share whether or not they have line-in, etc. in the playback mixer, it could be useful.
    -Dave
    ?[email protected]

  • How to make an indicator takes more than one input

    Hello,
    I want to know how to make an indicator ( like gauge for example) response to more than one case strrcuture result. In other words, how the indicator can take more than one input and move based on different input values ( the arrow of the gauge moves to different angles basesed on the logic structure and not only to one degree).
    Thanks in advance,
     

    YES, you got it right Coastal !
    This is what i want to do,
    I dont know how to establish this output in the software, i am still learning LabVIEW.
    I put a merge block to join the outputs but it didnt work.
    check it in the attached VI file.
    I am sure it is an easy thing but I dont know how to implement it.
    Any help you provide is appreciated,
    Best wishes 

  • How to make input field as mandatory field in sub screen

    Hi All,
           I need to display the input selection parameters in tab strip sub screen. The input screen is not giving an error while processing with blank values, but I made the input field as required in sub screen input filed settings. Can some one please help me how to make the input field as mandatory field in sub screen.
    Thanks in advance.
    Regards,
    Kannan

    Hi Kannan,
        Try this out.
    1. Goto screen painter
    2. Enter the program name and screen number ( screen # 1000 -  in case if its  a custom report prg)
    3. Double click on the field which u`ve got to make mandatory.You`ll get Screen painter attributes window.
    4. U`ll find three tabs here - Dict, Program, Display
    5. Go to Program tab, and change the first attribute - Input field`s input value as "Required".
    6. Save and activate it.
    7. Now execute ur program and this should make ur field as mandatory on the screen.
    This works with input fields, but I`m not sure about the input field in tab strip control.
    Hope this helps
    Regards,
    Farhana

  • How to make buttons enabled after the data is entered in JTextField?

    I got a JTextField. I want to test the entered data in JTextField is eight length. If the data is of length eight then i want to enable two buttons. How to make it enable? I am getting the length eight, but the buttons are not enable. What listeners I have to use.
    Can anybody help me out.
    Thanks for your help in advanced.

    Create a class that extends KeyAdapter. Add a field that is an array of buttons. Override the keyTyped(KeyEvent e) method to use getSource() to access the text area, check the length of the text, and if > 8, go through the array and enable the buttons in the array. Then, when you create the text area, create an instance of your listener, passing it an array of the two buttons you want to enable, and then use addKeyListener(yourKeyListener) to add your key listener to the text area.
    Doug

Maybe you are looking for

  • How can I view my pictures that were backed up to iTunes? I no longer have an apple product but need to view the pictures for very important reasons.

    How can I view my pictures that were backed up to iTunes? I no longer have an apple product but need to view the pictures for very important reasons.

  • Default value in advanced  search

    Hi All,           I want to give default values in "open advanced search" in opportunities. I need to give default as sy-datum in Validto field and start date of each quater as default for Validfrom field.                  I have written  the code to

  • User quotas on tablespace

    Hi, I created a tablespace and made it default to a user. immediateley i issued a command to apply a quota 0m for that user to that tablespace.Now when i am trying to create a table by logging on that newley created user and inserting the table on th

  • Load Runner - stress test for BI java report(WAD 7.0) error

    Dear all:                                                                                Our project implement the SAP Portal 7.0(NW2004s, BW/EP SP14) and before we go-live, we use the Load Runner 8.0 to test the performance of SAP BW Java reports. 1

  • Need help with updates

    I'm the second owner of my macbook, whenever I try to install updates it asks for the password for the former owner's apple id.  It won't allow me to change the username/apple id, so I cannot install updates.  Any ideas?