Java textField的setText()方法无效

来源:百度知道 编辑:UC知道 时间:2024/05/29 13:43:16
//部分主要代码
public class testTextField extends JFrame {

public testTextField(String title){
super(title);
initDialog();
}

JTextField txt1 = new JTextField(10);//为什么此文本框仍然为空???应该是hello才对呀。
public void setValue(String str){
txt1.setText("hello");

}

private JPanel initCenter(){
JPanel centerPanel = new JPanel();//用来容纳多个组件的容器
JPanel infoPanel = new JPanel();//该容器使用GridBagLayout来布局组件
GridBagLayout layout = new GridBagLayout();
infoPanel.setLayout(layout);//设置容器的布局管理器

JLabel lbl1 = new JLabel("商品编号:");
JLabel lbl2 = new JLabel("商品名称:");
JLabel lbl3 = new JLabel("规格型号:");
JLabel lbl4 = new JLabel("单位:");
JLabel lbl5 = new JLabel("品牌:");
JLabel lbl6 = new JLabel("颜色:");
JLabel lbl7 = new JLabel("当前库存:");
JLabel lbl8 = new JLabel("备

Java  textField的setText()方法无效的原因如下:

  1. textField没有初始化完成,导致setText()方法无法获取并执行。

  2. java代码存在其他错误,导致所有的对象没有生成,无法使用该方法。

  3. setText()填充的文本是空字符串,没有显示数据。

你把setText()写在setValue()中
但是你调用过setValue()吗

上面的都对,但是楼上的那个
new testTextField("my test").setValue("hello"); //调用这个方法就可以了,这样就初始化文本域了

}

JTextField txt1 = new JTextField(10);
public void setValue(String str){
txt1.setText("hello"); //改成txt1.setText(str);

}

public static void main(String[] args) {
// TODO Auto-generated method stub
new testTextField("my test").setValue("hello"); //调用这个方法就可以了,这样就初始化文本域了

}