TextField的getText()方法不起作用 [英] getText() method of TextField not working
本文介绍了TextField的getText()方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
if-else in actionPerformed()根本不起作用。有人请任何帮助我。谢谢
If-else in actionPerformed() is not working at all. Someone please any help me. Thank you
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class MyFileDialog implements ActionListener
{
FileDialog fd;
Button btn;
TextArea txtAr;
TextField txtPath;
GridBagLayout gblo;
GridBagConstraints gbc;
Frame frm;
Label lbl1;
MyFileDialog()
{
frm=new Frame("File Dialog");
frm.setVisible(true);
frm.setSize(700, 700);
frm.setLocation(250,250);
gblo=new GridBagLayout();
gbc=new GridBagConstraints();
frm.setLayout(gblo);
gbc.fill=GridBagConstraints.BOTH;
gbc.anchor=GridBagConstraints.CENTER;
//gbc.weightx=0.0;
gbc.insets.left=0;
gbc.insets.right=0;
//frm.add(lbl1=new Label("Enter file name: ",Label.LEFT));
//gblo.setConstraints(lbl1, gbc);
gbc.insets.left=2;
gbc.insets.bottom=5;
frm.add(txtPath=new TextField(30));
gblo.setConstraints(txtPath, gbc);
gbc.insets.left=5;
gbc.insets.top=5;
gbc.gridwidth=GridBagConstraints.REMAINDER;
frm.add(btn=new Button(" Load "));
btn.setSize(20,10);
gblo.setConstraints(btn, gbc);
btn.addActionListener(this);
gbc.insets.left=1;
gbc.gridwidth=2;
frm.add(txtAr=new TextArea("",20,70,TextArea.SCROLLBARS_BOTH));
frm.addWindowListener(new WindowAdapter()
{@Override
public void windowClosing(WindowEvent we)
{
frm.setVisible(false);
System.exit(0);
}});
}
@Override
public void actionPerformed(ActionEvent e)
{
String dir="";
if(txtPath.getText()==""||txtPath.getText()==null)
{
fd=new FileDialog(frm,"Load your file",FileDialog.LOAD);
fd.setVisible(true);
dir=fd.getDirectory()+fd.getFile();
txtPath.setText(dir);
}
else
dir=txtPath.getText();
loadFile(dir);
}
public void loadFile(String path)
{
try
{
FileInputStream fis=new FileInputStream(path);
int space=fis.available();
byte []buffer=new byte[space];
fis.read(buffer);
String fileContent=new String(buffer);
txtAr.setText(fileContent);
}
catch(IOException e)
{
txtAr.setText("File cannot be loaded");
}
}
public static void main(String args[])
{
new MyFileDialog();
}
}
推荐答案
你好,
尝试更改if条件,如下所示。
Hello,
Try changing your if condition as shown below.
if (txtPath.getText() != null && txtPath.getText().trim().length > 0)
dir=txtPath.getText();
else {
fd = new FileDialog(frm, "Load your file", FileDialog.LOAD);
fd.setVisible(true);
dir=fd.getDirectory() + fd.getFile();
txtPath.setText(dir);
}
您还可以使用 StringUtils.isEmpty
或 StringUtils.IsBlank
来自 commons lang library 一个用于执行字符串相关操作的null安全助手类。
问候,
You can also use StringUtils.isEmpty
or StringUtils.IsBlank
from commons lang library a null safe helper class for performing string related operations.
Regards,
这篇关于TextField的getText()方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文