如何在运行时设置JTextField的宽度?

Joh*_*ohn 3 java swing runtime jtextfield

有人可以帮助我如何设置JTextField运行时的宽度?我希望我的文本字段在运行时调整大小.它会询问用户的长度,然后输入将改变文本字段的宽度.

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();
}
Run Code Online (Sandbox Code Playgroud)

我正在使用null布局,因为我正处于编辑模式.

nIc*_*cOw 5

你只需要使用jTextFieldObject.setColumns(int columnSize).这将允许您在运行时增加它的大小.您不能在最后完成的原因是null布局.这null Layout/Absolute Positioning是不鼓励使用的主要原因之一.这是一个尝试的小例子:

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();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

对于绝对定位你需要调用setSize()JTextField,以实现结果,但你应该始终牢记,为什么这种做法是气馁,因为在给定的原因Java文档的第一款:

虽然可以不使用布局管理器,但是如果可能的话,应该使用布局管理器.布局管理器可以更轻松地调整依赖于外观的组件外观,不同的字体大小,容器的大小变化以及不同的区域设置.布局管理器也可以被其他容器以及其他程序轻松地重用.

  • 哦.:(我真的很喜欢在编辑之前的答案说..*"对于绝对定位......"*Eeek!让我们不要带领新手走向疯狂和怪物的道路.哦,好吧,反正+1.:) (2认同)