0

我想从 JtextField 中删除空格,因此当用户单击按钮时,它会自动从他/她编写的文本中删除空格。

4

3 回答 3

3

这将用空字符串替换每个空格:

String text = txtField.getText().replaceAll("\\s+", "");

// or just
// String text = txtField.getText().replace(" ", "");

如果您只需要删除尾随和前导空格,请执行以下操作:

String text = txtField.getText().trim();

最后将您的新文本设置到文本字段中:

textField.setText(text);
于 2013-04-08T13:00:27.377 回答
1
String sessi = textField.getText();
System.out.println(sessi.replaceAll(" ",""));

会为你工作。

于 2013-04-08T13:03:39.693 回答
1

简单地说,您需要为用户要单击的按钮添加一个动作侦听器。例如:该按钮将用于发布某些内容。“邮政”

public class YourProject extends JFrame implements ActionListener{

JtextField text = new JtextField();
JButton post = new JButton("POST");

public YourProject(){

add(text);
add(post);
post.addactionlistener(this);
setVisible(true);

}



 @Override
public void actionPerformed(ActionEvent e) {

if(e.getSource()==post) {

String removed = text.getText().trim();

System.out.println(removed);

}

如果用户写“Hello World”然后点击发布,输出将是“HelloWorld”。希望这可以帮助。

于 2013-04-08T13:09:57.513 回答