问题
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