Remove spaces from certain JtextField in java netbeans

爷,独闯天下 提交于 2019-12-12 01:57:23

问题


I want to remove spaces from a JtextField, so when the user click the button it automatically removes the space from the text he/she wrote.


回答1:


simply, you need to add an action listener to the button which the user is going to click. for example: the button will be for posting something. "POST"

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

}

If the user writes "Hello World" then clicks post, the output will be "HelloWorld". hope this helps.




回答2:


This would replace every space with empty string:

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

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

If you just need to remove trailing and leading spaces, then do this:

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

and finally set your new text into the text field:

textField.setText(text);



回答3:


String sessi = textField.getText();
System.out.println(sessi.replaceAll(" ",""));

would work for you.



来源:https://stackoverflow.com/questions/15879695/remove-spaces-from-certain-jtextfield-in-java-netbeans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!