简体   繁体   English

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

[英]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?有人可以帮助我如何在运行时设置JTextField的宽度吗? 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.我为此使用null布局,因为我处于编辑模式。

You simply need to use jTextFieldObject.setColumns(int columnSize) .您只需要使用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.你最后不能这样做的原因是null布局。 That is one of the main reasons why the use of null Layout/Absolute Positioning is discouraged.这是不鼓励使用null Layout/Absolute Positioning主要原因之一。 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 theJava Doc's first paragraph:对于绝对定位,您需要在JTextField上调用setSize()以获得结果,但您应该始终牢记不鼓励这种方法的原因,如Java Doc 的第一段中所述:

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.布局管理器也可以很容易地被其他容器以及其他程序重用。

I got the text field to resize just by using setBounds .我只是通过使用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();
    }
}

"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.注意:请注意,食用过多的蛋糕会导致您死亡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM