mani
mani

Reputation: 1044

Show the HTML code preview in JFrame?

I am writing a Java code which also consists of HTML. I want to preview that HTML code in JFrame only. Is there any solution available within the Java API?

Could you please guide me to solve this problem?

Upvotes: 1

Views: 3117

Answers (3)

Mikle Garin
Mikle Garin

Reputation: 10143

Actually, almost every Swing component that can display custom user text somewhere allows HTML instead of the text. For e.g. JButton text, JTabbedPane tab title, JTable cell/header, JLabel text, JList/JTree/JComboBox cell renderers, component tooltips and others.

To use HTML inside any of those - just add <html> tag at the very start of the text - that will be enough to let the view parser know that you have some HTML inside.

Also HTML that is supported in Java is pretty old and most of new features won't work as you could see them in modern browsers or visual editors. But its still more than enough to create some advanced components content where you need.

And one more thing - if you want to display some local images inside of the HTML you will have to change component's base location so it can properly load them:

component.putClientProperty (
    BasicHTML.documentBaseKey, 
    new File ( "/local/path/" ).toURI ().toURL () 
);

Some proper URL should be under that key (either local or remote).

Upvotes: 2

Andrew Thompson
Andrew Thompson

Reputation: 168825

JEditorPane supports a sub-set of the HTML 3.2 elements as well as simple styles (CSS). While this task could be achieved using CSS, the HTML 3.2 body element also accepts a bgcolor.

Web page with background color

import java.awt.Dimension;
import javax.swing.*;

class WebPageWithBackground {
    WebPageWithBackground() {
        String html = "<html><body bgcolor='#ffbb99'>Hi!";
        JEditorPane jep = new JEditorPane();
        jep.setContentType("text/html");
        jep.setText(html);
        jep.setPreferredSize(new Dimension(400,50));
        JOptionPane.showMessageDialog(null, jep);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new WebPageWithBackground();
            }
        });
    }
}

Upvotes: 2

Thomas Uhrig
Thomas Uhrig

Reputation: 31605

Yes. The JEditorPane can show (simple) HTML. See this JEditorPane tutorial for more details.

Upvotes: 4

Related Questions