gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:47:22 24 4
gpt4 key购买 nike

有人可以帮我如何在运行时设置 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();
}

我为此使用 null 布局,因为我处于编辑模式。

最佳答案

您只需使用 jTextFieldObject.setColumns(int columnSize) 。这将让您在运行时增加它的大小。您最终无法执行此操作的原因是 null 布局。这是不鼓励使用空布局/绝对定位的主要原因之一。这是一个供您尝试的小示例:

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();
}
});
}
}

对于绝对定位,您需要调用setSize()为了获得结果,尽管您应该始终牢记不鼓励这种方法的原因,如 Java Doc's 中给出的。第一段:

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.

关于java - 如何在运行时设置 JTextField 的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59803362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com