How to forbid the backspace in a JTextField?

Hello,
I'm trying to write a JTextField KeyListener that basically consumes all backspaces, so that anything input by the user in the field cannot be cancelled. (The user doesn't setText()).
How can I do that? It seems like I cannot!
I've tried by identifying '\b' and consume the KeyEvent, but then the backspace is still executed.

Lolz, ok I'm not sure of the use case, but lets have some fun.
One way would be to set the DocumentFilter
                ((AbstractDocument)jtf.getDocument()).setDocumentFilter(new DocumentFilter(){
                    @Override
                    public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
                        //Won't remove
                        //new Exception("remove " + offset + "," + length).printStackTrace();
                    @Override
                    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
                            throws BadLocationException {
                        if(offset == fb.getDocument().getLength()){
                            super.replace(fb, offset, length, text, attrs);
                });Just make sure that you remove the doc filter if you want to programmatically modify the value.
Edited by: Moot_Void on Mar 19, 2010 5:19 PM
Need to figure something out for replace too though.
Edited by: Moot_Void on Mar 19, 2010 5:34 PM
Added replace only allowed when the offset is at length of document.

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

  • Someone knows how to change the font of a JTextField ?

    I tried almost everything, but I still can't change the Font of a JTextField...
    Thanks anyway...

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing extends JFrame
      JTextField tf = new JTextField("Hello World");
      public Testing()
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocation(400,300);
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fonts = ge.getAvailableFontFamilyNames();
        final JComboBox cbo = new JComboBox(fonts);
        getContentPane().add(tf,BorderLayout.NORTH);
        getContentPane().add(cbo,BorderLayout.SOUTH);
        pack();
        cbo.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setFont(new Font((String)cbo.getSelectedItem(),Font.PLAIN,12));}});
      public static void main(String args[]){new Testing().setVisible(true);}
    }

  • How to set the text in a jtextfield to align to the left

    A quick simple question. I'm populating a jtextfield with text pulled from a record. However the text is too long to fit in the jtextfield and the alignment is set to the right rather than the left. How do I set the alignment of the text in the jtextfield to be on the left, so that the first character of the string is shown?
    I've tried using
    setHorizontalAlignmnet(JTextField.LEFT),
    but my text still appears right justified in the jtextfield. It means that the user has to scroll the text to go to the beginning of the string, rather than the usual of scrolling the right to go the end of the string.
    This has really gotten me stumped!

    HI thanks for the help. Unfortunately it doesn't work if the text is longer than the actual textfield. The textfield would still show the end of the text, rather than showing the beginning of the text.
    For e.g.
    |est text|
    is show rather than
    |test tex|
    which is my desired result.
    Any further suggestions please.

  • How to set the margin of a jtextfield when using standard lineborder

    Hi,
    I want to give my jtextfield a custom inset. The problem is that I also use a lineborder which controls the inset, thus when I try to the setMargin method, it doesn't work.
    Can anyone tell me how to do this?
    Much thanks
    Hugo Hendriks

    hello,
    try to use a compoundborder and add the lineborder and an emptyborder to it. by setting the emptyborders insets you can control the jtextpanes insets.
    i hope that one works =)
    bye

  • How to forbid the use of right click to open a pop up window  from a link ?

    I would like to prevent the user from opening pop up windows using the right button of the mouse on a link.
    Is it possible ?
    Thank you in advance for any help and suggestion.
    Paolo

    Is this regarding OAF ? if this is a requirement in OAF, then its not possible(unless you put in some javascript function in the page).
    If you want to do it in other jsps there are a lot of examples available in google on how to do this.
    Thanks
    Tapash

  • How to get the visible text in JTextField?

    I want to compare the space occupied by English and Japanese characters in the visible area of JTextFiled. I tried the same by taking the length of the characters occupied by the same text in both the language . But this did not work . I even tried the method getVisibleRect().
    Can please some one suggest a method or procedure by whcih i can get the length of the visible text in the JTextField
    Thanks
    Inder

    Point point = new Point(brm.getExtent(),0) ,it wont workWell, theoretically, the "Y" value shouldn't matter, but I guess when you display a line the text, the first couple of "Y" pixels are the spacing between lines and will presumably return the position of the character on the previous line (when using JTextArea, JTextPane). But since JTextField doesn't have a previous line I guess its returning 0. Change the "Y" value to 2 (1 doesn't work either):
    import java.awt.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              JTextField textField = new JTextField("Some text");
              frame.getContentPane().add(textField);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
              for (int i = 0; i < textField.getSize().width; i += 5)
                   Point p = new Point(i, 2);
                   System.out.print(p + " : ");
                   System.out.println( textField.viewToModel(p) );
    }

  • How to prevent the backspace conditionally. if no focus in any control in the document ?

    I prevent a backspace button conditionally using confirm box. i used event.preventdefault() method to stop the event of i press ok in the conform box.
    But it works when the focus is on either input or text area elements.
    if there is no focus in these controls the browser redirects to previous page.
    i need your help..
    thanks in advance !

    Hi dineshkumar,
    Thank you for your question. I understand that there are some default hot keys that are not being prevented in a web page unless they are focused in an input html tag. I do not know if this is for a website you developed or if this is for all websites, but:
    If it is for all websites: you can use a key configuration to change it only in Firefox [http://kb.mozillazine.org/Keyconfig_extension]
    If it is in a website:
    *Please see the MDN article for more information on the Javascript call you are using: [https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault]
    *Here is a relevant stack overflow question: [http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false]
    Thank you and we hope this helps.

  • Tracking the backspace key press??

    Hi
    I was trying to limit the no. of characters in a JTextField by using Inputverifier class.
    I am able to acheive that. But now the problem is I can't use backspace, arrow keys, etc.
    Since I am tracking key press event. I need to track backspace, arrow keys press too.
    How to track the backspace, arrow keys press?
    Here is my code:
    public class JTextInputVerifier extends InputVerifier
        int maxLength;
        JTextField jtf;
        public JTextInputVerifier(int maxLength) {
            this.maxLength = maxLength;
        public int getTextLimit()
            return maxLength;
        public boolean verify(JComponent c) {
            jtf = (JTextField)c;
            String str = jtf.getText();
            if (str.length() >= maxLength)
                return false;
            return true;
    final JTextInputVerifier inputVerifier = new JTextInputVerifier(10);
            txtCheck.setInputVerifier(inputVerifier);
            KeyListener input = new KeyListener() {
                public void keyTyped(KeyEvent e) {
                    if(!txtCheck.getInputVerifier().verify(txtCheck))
                        txtCheck.setText(txtCheck.getText().substring(0, inputVerifier.getTextLimit()));
                        java.awt.Toolkit.getDefaultToolkit().beep();
                public void keyPressed(KeyEvent e) {
                    throw new UnsupportedOperationException("Not supported yet.");
                public void keyReleased(KeyEvent e) {
                    txtCheck.setText(txtCheck.getText());
            txtCheck.addKeyListener(input);Please suggest some ideas.
    Is there any alternative way to restrict the no. of characters? which won't affect working of backspace, and other keys..?
    Praveen

    Joerg22 wrote:
    You could use a DocumentListenerThis won't work; DocumentListeners get notified after an insertion/deletion occurs. What you need to use is a javax.swing.text.DocumentFilter.

  • How can forbid changing data when using BAPI  'BAPI_MATERIAL_SAVEREPLICA'?

    I am using BAPI  'BAPI_MATERIAL_SAVEREPLICA' to creat material master data in batch.
    But this BAPI also can be used for change mode.
    How to forbid the change of MAT data when use this BAPI?
    TKS a lot~~
    I am looking foward to your response~~~

    you have to find out what the user did before your program goes ahead and starts the BAPI.

  • How to forbid Column-Moving in a JTable ?

    Hi,
    anyone knoyw how to forbid the Column-Moving in a JTable ??
    I have a JTable that works fine, but it is still allowed to move the columns. And i want to forbid that.
    This: JTableHeader header = new JTableHeader();
    header.setResizingAllowed(false);
    header.setReorderingAllowed(false);
    did not work :-\
    Maybe someone has some ideas and could help me?
    Thx and have a nice day
    Avalon

    >
    Where's your thread, GoldieDork? You do nothing
    besides trolling.no I don't, I ask Java questions but no one answers them apart from the database question where dave and jverd and rage were all nice to me and I was happy that we could all be friends cos they helped me but then they started cussing me again so thats why I no longer talk to those guys.
    I dont know where my thread is now, Sun probably deleted it

  • How can forbid changging data when using BAPI  'BAPI_MATERIAL_SAVEREPLICA'?

    I am using BAPI  'BAPI_MATERIAL_SAVEREPLICA' to creat material master data in batch.
    But this BAPI also can be used for change mode.
    How to forbid the change of MAT data when use this BAPI?
    TKS a lot~~
    I am looking foward to your response~~~
    Edited by: lorryhappy on Dec 22, 2009 11:35 AM

    Hi
    You can achieve it in another way..
    Before Passing Data to BAPI , Check whether the material is existing or not..
    If material is existing (Present in Material Master Tables e.g. MARA ) using
    data: l_matnr like mara-matnr.
    Select single matnr from mara into l_matnr.
    IF sy-subrc EQ 0.
    " Material is existing ==> Do Not Pass to BAPI
    else.
    " Material is NOT existing ==> Pass to BAPI for creation.
    endif.
    Repeat above logic for every material in batch..
    Hope it will solve your problem..
    Thanks & Regards
    ilesh 24x7
    ilesh Nandaniya

  • Help!! I can't find how to get the enter key......

    Hi...
    I am information technology student. I am now first year second semester
    I need help because I don't know how to catch the enter key in JTextField.
    I want to submit the form when user press the enter key in JTextField....
    I only can find KeyEvent.VK_ENTER ( actually that is not what I want)
    Another thing is
    "How to add a JMenuItem into a JMenuItem...."
    I want to do like this.... When you click the "Tools bar" in View item.. another menu comes out...???"
    He he... I hope you all can understand what I mean.. because I know my english is not so good... because I am from Myanmar.
    for(int i=0;i<1;i--)
    System.out.println("Thanks A lot");
    Thu Rein Nyo...
    You also can reply by e-mail.. thanks

    Hi...
    I am information technology student. I am now first
    year second semester
    I need help because I don't know how to catch the
    enter key in JTextField.it can be done easily by adding an actionListener to the JTextField. So when u enter something in the field and press enter the event will be caught and the code which u write in that will get executed.
    Eg:
    JTextField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    Your code comes here.
    Another thing is
    "How to add a JMenuItem into a JMenuItem...."
    I want to do like this.... When you click the "Tools
    bar" in View item.. another menu comes out...???"I think you are gettin confused with JMenu and JMenuItem. What u need to do is create a JMenu add another JMenu to it and add JMenuItems to it.. and ur problem will be solved.
    He he... I hope you all can understand what I mean..
    because I know my english is not so good... because I
    am from Myanmar.
    for(int i=0;i<1;i--)
    System.out.println("Thanks A lot");
    Thu Rein Nyo...
    You also can reply by e-mail.. thanks

  • How to prevent the Toolkit.getDefaultToolkit().beep() in JTextField

    Hi,
    I use the JTextField in my application.
    when the user type value in the field e.g. "123456"
    if you press the backspace 5 times the value will be "1" , pressing it again results with ""
    now.....
    pressing it again results a system beep.
    I want to prevent this beep how can I do it??
    thanks

    textField.getDocument().addDocuemntListener(docListener);
    Then implement the removeUpdate(DocumentEvent evt)
    Hope this helps
    Sai Pullabhotla

  • How to display the context of a Jbutton to a JTextField

    Hi,
    There is a key pad (1-9) on a GUI where each key is represented by a JButton. There is also a data entry filed, implemented using JTextField.
    However, when the user enters the ID using the key pad buttons each number should be displayed in the data entry field correspondingly (similar to calculator). I have already written the handlers for each button just don't know how to display the contexts in the text field, e.g. if the button 1 is pressed the 1 should be appeared in the text filed immediately. Anyone can help me to get this done?
    Thanks in advance,
    RMP

    Reza_mp wrote:
    .. Anyone can help me to get this done?In the actioPerformed method, call textField.setText( textField.getText() + "new data" )

Maybe you are looking for

  • Logic Studio 8 on a G4 dual 1.25?

    I've noticed the minimum requirements for running the Logic Studio 8 bundle is a G4 1.25 with 1gig ram, but G5 or Intel processor, as well as 2gig or more of ram recommended. I'm currently running Logic Express 7.2 on a G4 dual 1.25 with 2gigs of ram

  • Is there a way to output multiple waves to soundboard

    Working on two projects that could benefit from multiple sounds being played at once. 1st is a C64 SID emulator. The SID has 3 voices Each with there own ADSR and waveform. I can generate a single waveform with attack and decay and get decent sounds

  • Contacts not syncing & Calendar off by 1 hour

    Specs: 1st generation iPhone running 2.0.1 iMac 2.4 GHz Intel Core 2 Duo running 10.5.4 iTunes 7.7.1 Overview: My phone is not syncing properly and it's causing me to show up to meetings at incorrect times and not have contact information with me on

  • SSL Errors - Sec_error_unknown_issuer

    I've got this error message on a site that I KNOW has a valid SSL and CA Certficate however ONLY FF has this issue with the website. The SSL is from GeoTrust, valid until 10.21.15. It's difficult enough to get to this sticking support page, FF needs

  • Middleware-Replicating service transaction from CRM to R/3

    Hi Experts We are using the transaction SRVO( Service Transaction) in CRM and it has to be replicated to the R/3. Can anybody tell me 1.what is the load object for replicating this transaction ? 2.Do i need to make any settings in R/3 for the replica