How to make selected text in JTextArea into a String?

highlight, java, jtextarea, listener, swing

Solution

JTextArea doesn't have any built-in functionality that will do this, but:

In order for someone to select text, they have to click on the text area, drag and release the click. So, attach a MouseListener and implement the mouseReleased method to check if any text was selected, and if so to save it as a string:

public void mouseReleased(MouseEvent e) {
    if (textArea.getSelectedText() != null) { // See if they selected something 
        String s = textArea.getSelectedText();
        // Do work with String s
    }
}

Problem

I'm working on a simple word processor with java swing and layouts, and I'm trying to figure out how to make individual blocks of text bold, italics, or different font sizes instead of the whole block of text changing at once in my JTextArea. Is there some way to initialize a String as the user highlights the text in the JTextArea with their mouse? I would love it if there was some sort of ActionListener or something for JTextArea which could detect all this and easily save anything as a string, but I'm not sure if this is possible. Something like this would be great: ``` String selectedtext; JTextArea type; class TextPanel extends JPanel implements ActionListener { public TextPanel() { type = new JTextArea(); type.addActionListener(this); this.add(type); } public void actionPerformed(ActionEvent e) { selectedtext = e.getSelected(); } } ```

Original source