Reputation: 4112
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?
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);
}
}
Upvotes: 8
Views: 21772
Reputation: 59694
If you wanna remove only selected text then try this:
textArea.setText(textArea.getText().replace(textArea.getSelectedText(),""));
Hope this helps.
Upvotes: 1
Reputation: 879
For JavaFx TextArea you can use deleteText(IndexRange range) method to delete the selected text.
textArea.deleteText(textArea.getSelection());
To delete text based on index use deleteText(int start, int end) overloaded method
textArea.deleteText(startIndex, endIndex);
We can use replaceSelection(String replacement) method to delete the text, in fact deleteText internally uses replaceText method but deleteText method will improve the readability of the code.
Upvotes: 1
Reputation: 8127
txtArea.replaceSelection("");
this should be shorter and more effective.
Upvotes: 45