Link to home
Start Free TrialLog in
Avatar of OBCT
OBCT

asked on

Inserting HTML to a JTextPane

This is hard to explain but I'll do my best.

I'm doing a basic html document editing application for a client (my first job with java :) and what I'm trying to achieve is to read a html document and add the text (without the html tags) into a JTextPane.
So far this has been successful with the setPage() method.

The problem I am having is inserting html tags to selected text....bold for example..... So using a StringBuffer "<B>" is added to the start and "</B>" to the end.
When I do a System.out.println(selectedText), it prints out some of the html...

If you've ever used Dreamweaver for example, you'll see that you can select text, add bold tags and the text will appear bold without showing the inserted html tags.
How should I go about doing this?

If I haven't explained well enough, please let me know.

Cheers

-OBCT
SOLUTION
Avatar of maheshexp
maheshexp

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of maheshexp
maheshexp

Avatar of OBCT

ASKER

I think I've jumped in the deep end here. I'm having lots of trouble...

I'm trying out the HTMLEditorKit so give me a little bit and I'll see how I go.
My main problem is...
When I select some text from the JEditorPane (I'm using that now because it seems to have more functionality with html) and do a System.out.println(), it will print out any html that the text uses.

For example...

If I select 'Click here to email me'
It will print out 'Click <a href="myemail@email.com">here</a> to email me'

Is there any way to prevent html from being selected in the JEditorPane?
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
> Is there any way to prevent html from being selected in the JEditorPane?

you could disable the editable region of JEditorPane like :

JEditorPane x = new JEditorPane();
x.setEditable(false);
> I think I've jumped in the deep end here. I'm having lots of trouble...

Think that the best way to do that is to have an example, click the download link :
http://forum.java.sun.com/thread.jsp?thread=502981&forum=57&message=2379998

If you really want to display a html page like a web browser then here is a sample :
http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JEditorPane.html

Hope that helps . . .
Javatm
Or you could use this from the above sample :

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class Browser extends JFrame implements HyperlinkListener,
                                               ActionListener {
  public static void main(String[] args) {
    if (args.length == 0)
      new Browser("http://www.google.com/");
    else
      new Browser(args[0]);
  }

  private JButton homeButton;
  private JTextField urlField;
  private JEditorPane htmlPane;
  private String initialURL;

  public Browser(String initialURL) {

    super("Simple Swing Browser");

    this.initialURL = initialURL;

    JPanel topPanel = new JPanel();
    topPanel.setBackground(Color.lightGray);
    homeButton = new JButton("Home");
    homeButton.addActionListener(this);
    JLabel urlLabel = new JLabel("URL:");
    urlField = new JTextField(30);
    urlField.setText(initialURL);
    urlField.addActionListener(this);
    topPanel.add(homeButton);
    topPanel.add(urlLabel);
    topPanel.add(urlField);
    getContentPane().add(topPanel, BorderLayout.NORTH);

    try {
        htmlPane = new JEditorPane(initialURL);
        htmlPane.setEditable(false);
        htmlPane.addHyperlinkListener(this);
        JScrollPane scrollPane = new JScrollPane(htmlPane);
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    } catch(IOException ioe) {
       warnUser("Can't build HTML pane for " + initialURL
                + ": " + ioe);
    }

    Dimension screenSize = getToolkit().getScreenSize();
    int width = screenSize.width * 8 / 10;
    int height = screenSize.height * 8 / 10;
    setBounds(width/8, height/8, width, height);
    setVisible(true);
  }

  public void actionPerformed(ActionEvent event) {
    String url;
    if (event.getSource() == urlField)
      url = urlField.getText();
    else  // Clicked "home" button instead of entering URL
      url = initialURL;
    try {
      htmlPane.setPage(new URL(url));
      urlField.setText(url);
    } catch(IOException ioe) {
      warnUser("Can't follow link to " + url + ": " + ioe);
    }
  }

  public void hyperlinkUpdate(HyperlinkEvent event) {
    if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
      try {
        htmlPane.setPage(event.getURL());
        urlField.setText(event.getURL().toExternalForm());
      } catch(IOException ioe) {
        warnUser("Can't follow link to " 
                 + event.getURL().toExternalForm() + ": " + ioe);
      }
    }
  }

  private void warnUser(String message) {
    JOptionPane.showMessageDialog(this, message, "Error",
                                  JOptionPane.ERROR_MESSAGE);
  }
}
   
Hope that helps . . .
Javatm  
Avatar of OBCT

ASKER

>you need to stip the text out of the html

I just tried than and it shows up as normal text where as I need it to show any bold font, colored text etc
Am I going about this the right way?
Are you doing an editor keyword highlighting on html document ?
Avatar of OBCT

ASKER

Sorry, I dont understand...what do you mean?
> Sorry, I dont understand...what do you mean?

Are you trieng to create a html editor like dreamweaver ?

If Yes then I can help you about it cause I've created an example just
for this question.
Avatar of OBCT

ASKER

Yes I am.
I can give you the link and you can download it is that okey :)
Avatar of OBCT

ASKER

Yeh thats fine, cheers.
I've done my best and here is a simple example :
http://velasquez.2.forumer.com/index.php?showtopic=13&st=0&

Click on the Editor.zip to download it.

Hope that helps . . .
Javatm
Avatar of OBCT

ASKER

Thanks Javatm, that's helped me alot however I don't think I'm explaining my problem well enough so I'll try once more...

I have loaded a html page into my JEditorPane using the setPage() method.
In doing this, any html tags that effect the appearance of the text will show up in the text area. E.g. any fonts with <b>mytext</b> will appear bold and the tags will be hidden.

When a user selects some text and clicks the bold button, the aim is to add the bold tags onto the string then replace the selected string with the newly appended string and somehow hide the bold tags so the text will appear bold without the tags being visible.

I'm using this method to add the tags and attempt to replace the text but that’s when the dramas occur.

public static void addBoldTags()
{
     int start = HtmlEditorGUI.htmlTextBox.getSelectionStart();
     int end   = HtmlEditorGUI.htmlTextBox.getSelectionEnd();

     String selection = HtmlEditorGUI.htmlTextBox.getText().substring(start, end);

     System.out.println(selection);

     StringBuffer newText = new StringBuffer(selection);

     newText.insert(selection.length(), "<b>");
     newText.insert(0, "</b>");

     HtmlEditorGUI.htmlTextBox.replaceSelection(newText.toString());
}

If you can somehow try selecting some text in a JEditorPane that has had the setPage() method used.....(so google for example shows up)....you will notice the selected text contains html tags.
Please let me know if this makes sense.

Thanks for all your help so far.

Cheers

-OBCT
I'm quite having a problem understanding your situation actually there many things that we have
to consider, can you submit the codes on the the site that I gave you above so that I can see
and try to debug the codes thanks.

Javatm
As I said above you need to parse the html to extract the text.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just dont forget to import :

import javax.swing.text.*;

To view the solution and the example go here :
http://velasquez.2.forumer.com/index.php?showtopic=13

Hope that helps . . .
Javatm
Avatar of OBCT

ASKER

Have a look at the following class. It's a simplified version of what I'm doing. I'll make more comments at the bottom.

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import javax.swing.*;
import javax.swing.text.*;
import javax.swing.text.html.*;

public class Demo extends JFrame implements ActionListener
{
    JPanel      mainPanel;
    JEditorPane htmlTextBox;
    JTextPane   viewTextBox;
    JButton     addBoldBtn;
    JScrollPane scrollPane;

    public Demo() throws IOException
    {
        mainPanel   = new JPanel(new BorderLayout());
        htmlTextBox = new JEditorPane("http://www.google.com");
        addBoldBtn  = new JButton("Add bold tags");
        scrollPane  = new JScrollPane(htmlTextBox);

        addBoldBtn.addActionListener(this);
        scrollPane.setPreferredSize(new Dimension(300,200));

        mainPanel.add(addBoldBtn, BorderLayout.PAGE_START);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().add(mainPanel);
        setResizable(false);
        setSize(500,500);
        setVisible(true);

    }

    public void actionPerformed(ActionEvent e)
    {
        String selection = htmlTextBox.getSelectedText();

        System.out.println(selection);

        StringBuffer newText = new StringBuffer(selection);

        newText.insert(selection.length(), "</b>");
        newText.insert(0, "<b>");

        htmlTextBox.replaceSelection(newText.toString());
    }

    public static void main(String[] args)
    {
        try   { Demo d = new Demo(); }
        catch (IOException e) { e.printStackTrace(); }
    }
}

My first problem was I wasn't using common sense, so I've fixed alot of small problems.
When you run this class, the frame will show and googles' website will apear in the JEditorPane. The html isn't visible but any text that has a link, bold etc will show up as it should on a webpage.
Select any text and click the "Add bold tags" button, then you'll see '<B>' and '</B>' appended on the start and end of the selected text.
How am I meant to hide the bold tags that I'm adding to the text and have that text formatted so it appears as bold in the JEditorPane.
The people using this won't have any knowledge of html so having a html view isn't an option.
Did you try my other solution ?
because the easiest way to do that is the way I did it, see my comments above :)
Avatar of OBCT

ASKER

Yes I did but the users wont know any html so they're not going to know what the syntax means if they see it.
Is there any method avaliable that get the JEditorPane to read its content (including html tags) and re-read/reparse the content so the text that has been changed will now show up as being bold???
> Yes I did but the users wont know any html so they're not going to know what the syntax means if they see it.

You told me that you are creating an editor like Dreamweaver, that's why I gave you  an example.
Your project seems to be hard its like a browser, the problem w/ that is you want to edit the
webpage it self.

You want to do it in a single frame ? in that case then you need to make a temporary file which
will get the page from JEditorPane and save it in a file so that when you want to edit it its there
hidden in a temporary file.

Then again what I gave you should already be a normal standard of an html editor.
Avatar of OBCT

ASKER

I got it working using this :)

String       htmlText   = htmlTextBox.getText();
String       newText    = htmlTextBox.getSelectedText();
StringBuffer newTextSb  = new StringBuffer(newText);
StringBuffer htmlTextSb = new StringBuffer(htmlText);

int start = htmlText.indexOf(newText);
int end   = start + newText.length();

try
{
    htmlTextSb.insert(end,  "</b>");
    htmlTextSb.insert(start, "<b>");
}
catch (StringIndexOutOfBoundsException ex)
{
    System.out.println("Text already bold");
}

htmlTextBox.setText(htmlTextSb.toString());

Thank you both for all your help. I couldn't have done it without you :)

Cheers

-OBCT
http://www.freewebs.com/cube-j

Always there to help . . .
Friend : Javatm