java 仅删除文本区域中的选定文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5255466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
deleting only a selected text in a text area
提问by Pavithra Gunasekara
I want to delete selected text in a text area using Java Swing, but I couldn't find a way to do that. At some point I thought of using textArea.setText("");
but, when I do, it clears out everything. Can some one please help me with this?
我想使用 Java Swing 删除文本区域中的选定文本,但找不到方法。在某些时候我想过使用,textArea.setText("");
但是当我这样做时,它会清除所有内容。有人可以帮我解决这个问题吗?
Here is the code I've written so far,
这是我到目前为止编写的代码,
public class DeleteTest extends JFrame implements ActionListener {
JPanel panel;
JTextArea textArea;
JButton button;
public DeleteTest() {
setVisible(true);
setSize(500, 500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
panel.setBackground(getBackground().BLACK);
textArea = new JTextArea(300, 300);
button = new JButton("clear");
button.addActionListener(this);
panel.add(button);
add(textArea, BorderLayout.CENTER);
add(panel, BorderLayout.SOUTH);
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource()==button){
String selected=textArea.getSelectedText();
if(!selected.equals("")){
}
}
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
DeleteTest de = new DeleteTest();
}
};
SwingUtilities.invokeLater(r);
}
}
}
采纳答案by Harry Joy
If you wanna remove only selected text then try this:
如果您只想删除选定的文本,请尝试以下操作:
textArea.setText(textArea.getText().replace(textarea.getSelectedText(),""));
Hope this helps.
希望这可以帮助。
回答by secmask
txtArea.replaceSelection("");
this should be shorter and more effective.
这应该更短,更有效。
回答by prasadg
For JavaFx TextAreayou can use deleteText(IndexRange range)method to delete the selected text.
对于JavaFx TextArea,您可以使用deleteText(IndexRange range)方法删除所选文本。
textArea.deleteText(textArea.getSelection());
To delete text based on index use deleteText(int start, int end)overloaded method
要根据索引删除文本,请使用deleteText(int start, int end)重载方法
textArea.deleteText(startIndex, endIndex);
We can use replaceSelection(String replacement)method to delete the text, in fact deleteTextinternally uses replaceTextmethod but deleteTextmethod will improve the readability of the code.
我们可以使用replaceSelection(String replacement)方法来删除文本,实际上deleteText内部使用replaceText方法但是deleteText方法会提高代码的可读性。