Hugo
Hugo

Reputation: 323

Select single word or string (doubleclick) in order to edit

I'm testing the functions of text editor and I would like to be able to select text (either a word or a string between 'p' tags) and then edit it by clicking a button (B for bold or I for Italic). Much like the editor used here at Stackoverflow. This will add an html B tag so that it shows as bold. I know the following Xpath leads to a string of text but I can't find how to select this text or how to select a word in this text.

This is part of the page source (text editor is in an iframe)

<html>
  <head>
    <body>
      <p>
        This is a line of text to test Bold
      </p>
      <p>
        This is a line of text to test Italic
      </p>
     </body>

Where this

driver.findElement(By.xpath("/html/body/p[1]")

leads to a text:

This is a line of text to test Bold

I would like to select the word 'Bold' (or the entire sentence if this is easier) and then click a button above the text to make it Bold

Upvotes: 0

Views: 644

Answers (2)

Ketan Sethi
Ketan Sethi

Reputation: 124

Try this

Actions a = new Actions(driver);
a.doubleClick(driver.findElement(By.xpath("/html/body/p[1]")).build().perform();

Upvotes: 1

LordAnomander
LordAnomander

Reputation: 1123

What you could do is to use an <html> Tag within JLabels for instance.

What I have in mind looks like the following:

boldButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
            String formattedText = "<html><b>" + text + "</b></html>";
            label.setText(formattedText);
       }
}

italicButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
            String formattedText = "<html><i>" + text + "</i></html>";
            label.setText(formattedText);
       }
}

Unforunately, I do not know how your text editor looks like, but this is the way I would approach the problem.

Anyways, in a larger scale you can still use HTML tags to format the text (e.g., in a TextArea). In order to get the highlighted/selected items you might want to have a look at this thread how to get highlighted text in jtextarea.

So you could try something like this:

// retrieve selected text from text area
String selectedText = textArea.getSelectedText();
// get whole text
StringBuffer text = new StringBuffer(textArea.getText());
// remove the selected text
text.remove(textArea.getSelectionStart(), textArea.getSelectionEnd());
// make the selected text, e.g., bold.
selectedText = "<b>" + selectedText + "</b>";
// add the bold text to the whole text
text.insert(textArea.getSelectionStart(), selectedText);
//eventually apply outer <html> tags
String result = "<html>" + text.toString() + "</html>";
// set new text (with bold element) to the text area
textArea.setText(result);

Please note that I have not tried this, so you might tweak some things in order to make it work.

Upvotes: 1

Related Questions