有人可以帮我如何设置 a 的宽度吗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
布局。这是使用的主要原因之一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();
}
});
}
}
对于绝对定位,您需要调用setSize() on the JTextField
为了达到结果,尽管您应该始终牢记不鼓励这种方法的原因,如Java 文档第一段:
尽管可以不使用布局管理器,但如果可能的话,您应该使用布局管理器。布局管理器可以更轻松地调整依赖于外观和感觉的组件外观、不同的字体大小、容器大小的变化以及不同的区域设置。布局管理器还可以很容易地被其他容器以及其他程序重用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)