change the size of JTextField on KeyPress

前端 未结 4 1085
臣服心动
臣服心动 2021-01-28 07:12

I have to extend the size of JTextField on KeyPressed event as user enter the text in textfield.please give me some idea how to achieve this?

thanks in advance

4条回答
  •  执念已碎
    2021-01-28 07:41

    The best way I can think of is to add one CaretListener to the JTextField concerned, and with the change in the length of the Document, you Increase/Decrease the columns of the said JTextField by calling it's setColumns(...), which inturn will Increase/Decrease the size of the JTextField

    Here is one example to show you, how to achieve this :

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    
    public class JTextFieldColumnExample
    {
        private int columns = 1;
        private JTextField tfield;
    
        private void displayGUI()
        {
            JFrame frame =  new JFrame("JTextField Columns Example");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            final JPanel contentPane = new JPanel();
            tfield = new JTextField();
            tfield.setColumns(columns);
            tfield.addCaretListener(new CaretListener()
            {
                public void caretUpdate(CaretEvent ce)
                {
                    int len = tfield.getDocument().getLength();
                    if (len > columns)
                        tfield.setColumns(++columns);
                    else
                    {
                        if (--columns != 0)
                            tfield.setColumns(columns);
                        else
                        {
                            columns = 1;
                            tfield.setColumns(columns);
                        }   
                    }   
                    contentPane.revalidate();
                    contentPane.repaint();
                }
            });
    
            contentPane.add(tfield);
    
            frame.setContentPane(contentPane);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String... args)
        {
            SwingUtilities.invokeLater(new Runnable()
            {
                public void run()
                {
                    new JTextFieldColumnExample().displayGUI();
                }
            });
        }
    }
    

提交回复
热议问题