displaying jtextfield data in jlablel on keyPressed event

39 views Asked by At

i need to erase data in jlabel via jtextfield whenever i pressed backspace or delete from current position.I figure out how to add data in jlable(numeric data) but don't know how to erase it or edit it.

//this is my code

            String  str = "";

       private void jTextField1KeyPressed (java.awt.event.KeyEvent evt) {                                       

           char ch=evt.getKeyChar();

            if(Character.isDigit(ch)
               str += ch; 

            jLabel2.setText(str);
        }



} 
1

There are 1 answers

0
MadProgrammer On
  • Use a DocumentListener instead of a KeyListener, it will be able to detect when the user pastes text into the field and/or is changed programmatically
  • When the Document is updated, get the text from the field and set the labels text. There is little benefit in trying to update another String when the information is already available in the field/Document. If you "really" have to, use a StringBuilder instead, it's more efficient and is mutable

For example

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel mirrorLabel;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            JTextField field = new JTextField(10);
            field.getDocument().addDocumentListener(new DocumentListener() {

                @Override
                public void insertUpdate(DocumentEvent e) {
                    updateLabel(e.getDocument());
                }

                @Override
                public void removeUpdate(DocumentEvent e) {
                    updateLabel(e.getDocument());
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    updateLabel(e.getDocument());
                }

                protected void updateLabel(Document document) {
                    try {
                        mirrorLabel.setText(document.getText(0, document.getLength()));
                    } catch (BadLocationException ex) {
                        ex.printStackTrace();
                    }
                }
            });
            add(field, gbc);

            mirrorLabel = new JLabel(" ");
            add(mirrorLabel, gbc);
        }

    }

}