John
John

Reputation: 838

How to set the width of a JTextField at runtime?

Can someone please help me how to set the width of a JTextField at runtime? I want my text field to be resized on runtime. It will ask the user for the length, then the input will change the width of the text field.

if(selectedComponent instanceof javax.swing.JTextField){
    javax.swing.JTextField txtField = (javax.swing.JTextField) selectedComponent;
    //txtField.setColumns(numInput); //tried this but it doesn't work
    //txtField.setPreferredSize(new Dimension(numInput, txtField.getHeight())); //also this
    //txtField.setBounds(txtField.getX(), txtField.getY(), numInput, txtField.getHeight()); 
    //and this
    txtField.revalidate();
}

I am using null layout for this, since I'm on edit mode.

Upvotes: 3

Views: 6650

Answers (3)

Neuron
Neuron

Reputation: 5833

"Fun" little run-it-yourself solution:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JTextField jTextField = new JTextField("Alice");
    JPanel panel = new JPanel();
    JButton grow = new JButton("DRINK ME");
    JButton shrink = new JButton("EAT ME");
    panel.add(jTextField);
    panel.add(grow);
    panel.add(shrink);
    frame.add(panel);
    frame.setVisible(true);
    frame.pack();
    grow.addActionListener(l -> resize(frame, jTextField, 2));
    shrink.addActionListener(l -> resize(frame, jTextField, 0.5f));
}

private static void resize(JFrame frame, Component toResize, float factor) {
    System.out.println(toResize.getPreferredSize());
    toResize.setPreferredSize(new Dimension((int)(toResize.getPreferredSize().width * factor),
                                            (int)(toResize.getPreferredSize().height * factor)));
    toResize.setFont(toResize.getFont().deriveFont(toResize.getFont().getSize() * factor));
    frame.pack();
}

Attention: Please note that the consumption of too much cake can kill you.

Upvotes: 0

nIcE cOw
nIcE cOw

Reputation: 24626

You simply need to use jTextFieldObject.setColumns(int columnSize). This will let you increase it's size at runtime. The reason why you couldn't do it at your end is the null Layout. That is one of the main reasons why the use of null Layout/Absolute Positioning is discouraged. Here is a small example for trying your hands on :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JTextFieldExample
{
    private JFrame frame;
    private JPanel contentPane;
    private JTextField tfield;
    private JButton button;
    private int size = 10;

    private ActionListener action = new ActionListener()
    {
        public void actionPerformed(ActionEvent ae)
        {
            String input = JOptionPane.showInputDialog(
                                frame, "Please Enter Columns : "
                                                , String.valueOf(++size));
            tfield.setColumns(Integer.parseInt(input));                 
            contentPane.revalidate();
            contentPane.repaint();
        }
    };

    private void createAndDisplayGUI()
    {
        frame = new JFrame("JTextField Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           

        contentPane = new JPanel();
        contentPane.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));

        tfield = new JTextField();
        tfield.setColumns(size); 

        JButton  button = new JButton("INC Size");
        button.addActionListener(action);

        contentPane.add(tfield);
        contentPane.add(button);

        frame.getContentPane().add(contentPane);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String... args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                new JTextFieldExample().createAndDisplayGUI();
            }
        });
    }
}

For absolute positioning you need to call setSize() on the JTextField in order to attain the result, though you should always keep in mind the reason why this approach is discouraged, as given in the Java Doc's first paragraph:

Although it is possible to do without a layout manager, you should use a layout manager if at all possible. A layout manager makes it easier to adjust to look-and-feel-dependent component appearances, to different font sizes, to a container's changing size, and to different locales. Layout managers also can be reused easily by other containers, as well as other programs.

Upvotes: 6

Matthew Adams
Matthew Adams

Reputation: 10126

I got the text field to resize just by using setBounds. Check out the following example:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Resize extends JFrame{
    public JTextField jtf = new JTextField();

    public Resize(){
    //frame settings
    setTitle("Resizable JTextField");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);
    setSize(new Dimension(600,400));
    setResizable(false);

    //init and add text field to the frame
    add(jtf);
    jtf.setBounds(20,50,200,200);

    //button to change text field size
    JButton b = new JButton("Moar.");
    add(b);
    b.setBounds(20,20,b.getPreferredSize().width,b.getPreferredSize().height);
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent evt){
            jtf.setBounds(20,50,jtf.getSize().width+10,jtf.getSize().height); //THIS IS WHERE THE RESIZING HAPPENS
        }
        });

    setVisible(true);
    }
    public static void main(String[] args){
    Resize inst = new Resize();
    }
}

Upvotes: 1

Related Questions