XML in JEditorPane

Hi all,
I want to display an XML document with xsl in JEditorPane. Can it possible, If yes then how ?
Thanks in advance.

hi there, I think it should be possible, if you need the code you can find it under the link I add below.... just look through it and see if you understand what is done there...
if you don't, please feel free to contact me via mail(just get my profile :))
http://www.db.informatik.uni-kassel.de/~morad/xmlViewer/

Similar Messages

  • Displaying XML in JEditorPane

    Hi!
    Can someone please please help me, I'm new to java and having problems. IT migh tbe simple for you guys out there but its troubling me, been tryign to sort it out but no luck yet.Hopefully someone can help me out :)
    I'm currently uing a JEditorPane to display a HTML page which works fine. But I wanted it to display a XML page. The XMLfile with its DTD and XSL file loads up correctly in IE so theres no problem with syntax of these files. All i wanted it to do is display it on a JEditorPane. Am i right in thinking that JEditorPane is the right component to use. And if not then how do i solve this problem???
    Ive used the following code to call the xml file, it compiles and displays the actual code of the XML file not the visuals. Can someone please have a look.
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.io.IOException;
    public class testing extends JFrame
         public testing()
         { super("Testing");
              //Create an editor pane
              JEditorPane editorPane = createEditorPane();
              JScrollPane editorScrollPane = new JScrollPane(editorPane);
              editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              editorScrollPane.setPreferredSize(new Dimension(600,600));
              JPanel p = new JPanel();
              p.add(editorScrollPane);
              p.setBorder(BorderFactory.createCompoundBorder(
                                            BorderFactory.createTitledBorder("Styled Text"),
                                            BorderFactory.createEmptyBorder(20, 20, 20, 20)));
              JPanel contentPane = new JPanel();
              BoxLayout box = new BoxLayout(contentPane, BoxLayout.X_AXIS);
              contentPane.setLayout(box);
              contentPane.add(p);
              setContentPane(contentPane);
         private JEditorPane createEditorPane()
         {     JEditorPane editorPane = new JEditorPane();
         editorPane.setEditable(false);
         String s = null;
         try {
                        s =
                        "file:"
                                  + System.getProperty("user.dir")
                                  + System.getProperty("file.separator")
                                  + "directory.xml";
                             System.out.println(s);
                        URL helpURL = new URL(s);
                        displayURL(helpURL, editorPane);
                   catch(Exception e)
                   { System.err.println(" Couldn't create help URL : " + s);
                   return editorPane;
         private void displayURL(URL url, JEditorPane editorPane)
         {     try {
                             editorPane.setPage(url);
                        catch (IOException e)
                        { System.err.println("Attempted to read a bad URL : " +url);
         public static void main(String[]args)
         {     JFrame frame = new testing();
              frame.addWindowListener(new WindowAdapter()
              { public void windowClosing(WindowEvent e)
                   { System.exit(0);}
              frame.pack();
              frame.setVisible(true);
    }Thanks a lot. Would really appreciate any help.

    Hey
    Thanks for the help. I did use the XSLT transformation to ocnvert the xml into html. I used the following code :
    import javax.xml.transform.*;
    import javax.xml.transform.stream.*;
    import java.io.*;
    public class JavaTransform1
         public static void main(String args[])
         { try
                   TransformerFactory tf = TransformerFactory.newInstance();
                   Transformer transformer = tf.newTransformer(new StreamSource(new File(args[1])));
                   transformer.transform(new StreamSource(new File(args[0])),
                   new StreamResult(new File(args[2])));
              catch(Exception e) {}
    }Then using the command prompt i typed:
    java Transform1 directory.xml directory.xsl results.html
    This creates a HTML file but for some reason its blank :s
    I'm not sure why that is, when i call the html file in the JEditorPane it loads up a blank page which is what it looks like. for some reason even though it does create a HTML file its blank and not based on the XML file. What am I doing wrong here??
    Thanks alot.
    nat :)

  • Display XML in JEditorPane

    Hi,
    I have the XML and dtd on hand. Are there some code examples of how
    I can display it, or any references I can use?
    Thanks,
    Pin

    Ruskin wrote:
    I don't want to create an xml editor, ... I just want to check if everything is there, ...XML validation against an XSD can be done using core J2SE. That is what I offer in [(Yet Another) XML Validator|http://pscode.org/xml/xmltools.html#yaxv] (YAX-V).
    YAX-V provides a list of errors on the bottom left. If you click on one, it selects the line in the source XML (upper left) that it is refering to.

  • HTML held in DOM (as XML) rendered onto JEditorPane

    I am interested to know if anyone out there has any ideas on the following?:
    I am holding an html document as a DOM object as it is part of an xml message (which undergoes various transformations) that is passed through our software.
    The problem is that to do this I have had to make the html into a 'well-formed' xml document (which doesn't conform to html 3.2)
    Basically this causes problems where I want to use html elements that forbid end tags (e.g. <br> or <img>), in that the DOM when written out contains these end tags (so <br> becomes <br></br> or
    This actually works fine in IE (as it's quite lenient to these things) but when you put it in a JEditorPane it displays a spare > (not quite sure on it's logic!).
    So... does anyone have any good ideas?? My only thought was to extend the HTMLEditorToolKit to be more lenient with these but that strikes me as being a bit hard! I know I can get around it by putting spaces in for things like img (e.g. <img src="bla.gif"> </img> displays fine whereas <img src="bla.gif"></img> displays the image and then a > symbol!)

    If anyone is still interested in this tread, an article was written on this subject and ways to work around it:
    http://www.xml.com/pub/a/2000/08/30/xsltandhtml

  • JEditorPane - How to display XML Linked HTML File in JEditorPane ?

    Dear Friends,
    I have a HTML File consisting of stylesheet, xml linked (for data) and with headers, footers...
    When i called a ordinary html file using setpage property of JEditorpane..it's working no problem...but when i call the html file having xml linked or buttons...it's not properly displayed....
    If anybody hits this problem....pls...help me....
    Regards,
    V.Prasanna

    If you only need to display it, consider your HttpServletRequest just as byte stream. :) Just read from ServletInputStream and write it back into ServletOutputStream of HttpServletResponse.
    If you want to process incoming XML, please give some details first, what exactly you want to do. :)

  • JEditorPane xml/xsl to html

    I have build a little and simple xml/xsl parser that recive the xml file and the xsl file and return me a String that rapresent an html document respecting the input files.
    Now, i try to put this string ina JEditpr Pane but if i set as ContentType text/html i just see a white background and if I set, again, as contentType text/plain I can read the html code that i need.
    Sorry if this could be a stupid question, I'm a newbie in Swing.
    thx to all
    0m4r
    here is a little example of what I do
    JEditorPane jep = new JEditorPane();
    jep.setContentType("text/html");
    jep.setText(returnStringFromXMLParser);

    this could be the problem
    <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">i try to not use this line of code and it works fine...ut the promlem is that this line is added ny the XMLParser...what can I do?
    the Transformer I use:
    public static String toHTML(Document doc, String xslSource){
            ByteArrayOutputStream testo = new ByteArrayOutputStream();
            try{
                DOMSource source = new DOMSource(doc);
                TransformerFactory tFactory = TransformerFactory.newInstance();
                System.out.println("----> " + xslSource);
                Transformer transformer = tFactory.newTransformer(new StreamSource(xslSource));
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                transformer.setOutputProperty("encoding","iso-8859-1");   
                transformer.transform(source, new StreamResult(testo));
            }catch(Exception ioe){
                System.out.println("2 XMLTool.toHTML " + new java.util.Date());
                System.out.println(ioe);        
            return testo.toString();
        }

  • How to display Xml in a JEditorPane(in an applet)

    Hi All,
    I have an applet and i want to display xml in a JEditorPane in an applet. This xml document has a xsl attached to it for transformation. How can i do the transformation??
    Help or sample code or link to a sample code is highly appreciated!!!!
    Thanks
    Ragu

    Look this servlet which does a transformation. JEditorPane could call this servlet (with the method setPage) to do the transformation:
    public class SampleXSLTServlet extends javax.servlet.http.HttpServlet {
    public final static String FS = System.getProperty("file.separator");
    // Respond to HTTP GET requests from browsers.
    public void doGet (javax.servlet.http.HttpServletRequest request,
    javax.servlet.http.HttpServletResponse response)
    throws javax.servlet.ServletException, java.io.IOException
    // Set content type for HTML.
    response.setContentType("text/html; charset=UTF-8");
    // Output goes to the response PrintWriter.
    java.io.PrintWriter out = response.getWriter());
    try
    javax.xml.transform.TransformerFactory tFactory =
    javax.xml.transform.TransformerFactory.newInstance();
    //get the real path for xml and xsl files.
    String ctx = getServletContext().getRealPath("") + FS;
    // Get the XML input document and the stylesheet, both in the servlet
    // engine document directory.
    javax.xml.transform.Source xmlSource =
    new javax.xml.transform.stream.StreamSource
    (new java.net.URL("file", "", ctx+"foo.xml").openStream());
    javax.xml.transform.Source xslSource =
    new javax.xml.transform.stream.StreamSource
    (new java.net.URL("file", "", ctx+"foo.xsl").openStream());
    // Generate the transformer.
    javax.xml.transform.Transformer transformer =
    tFactory.newTransformer(xslSource);
    // Perform the transformation, sending the output to the response.
    transformer.transform(xmlSource,
    new javax.xml.transform.stream.StreamResult(out));
    // If an Exception occurs, return the error to the client.
    catch (Exception e)
    out.write(e.getMessage());
    e.printStackTrace(out);
    // Close the PrintWriter.
    out.close();

  • JEditorPane + XML + XSLT

    Hello, i have a little problem with a JEditorPane. Well, i have a XML file with XSLT and i want to put it in a JEditorPane. The problem is that i can see the XML but without the Stylesheet. I can't understand what is wrong.
    Please if you have any idea update me.
    Thanks, Ioannis.

    yep: kill the temp file, perform the XSLT in RAM only (for ex, output the XSLT result in a StringWriter or a ByteArrayOutputStream) and directly feed the result to the JTextArea or whatever...

  • View xml/xsl with JEditorPane

    After searching the forum and with no result
    1.How can i see inside JEditorPane a xml file like the Broser(with the functionlaty to expand/collpase the tree)?
    2.i want to see inside JEditoePane an XML file which have a link to its xsl file
    at the end i want to see it like regular Browser
    is it an straight task or it involves something more complicated?
    Please help me
    yoav

    there is a very good homepage, where you can download code from an xmleditor: http://www.manning.com/sbe/files/swing2e/swing2e.html
    (chapter 23)

  • Loading JEditorPane from an XML file parsed by

    an XSL translator.
    the JEditorPane setPage needs a URL, I'm wondering if there is anyway way to have the XSL tool write directly to the JEditorPane?

    If the XSL translator is producing HTML, and it can be run at the command line and send its output to stdout (as many of them can), then there's an approach to a solution.
    JEditorPane has a read() method that takes an InputStream as a parameter. You could use Runtime.getRuntime().exec() to run the XSL translator, then use getInputStream() from the resulting Process object to capture its output, and give that InputStream to JEditorPane.read().
    That's an outline of what I would try. Runtime.exec() is a notoriously irritating thing to get working, so it might fail, but you could give it a try.

  • How can an applet retrieve the values of a HTML form shown in a JEditorPane

    Hi,
    I'm doing an applet that contains a JTree and a JEditorPane
    among other components. Each node of the JTree represents some
    information that is stored in a database, and whenever a JTree
    node is selected, this information is recovered and shown in
    the JEditorPane with a html form. To make the html form,
    the applet calls a servlet, which retrieves the information of
    the node selected from the database. This information is stored
    like a XML string, and using XSLT, the servlet sends the html
    form to the applet, which shows it in the JEditorPane.
    My problem is that I don't know how I can recover new values
    that a user of the application can introduce in the input fields
    of the html form. I need to recover this new values and send them
    to another servlet which store the information in the database.
    If someone could help me I'd be very pleased.
    Eduardo

    At least I found a fantastic example. Here it is:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.net.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    public class FormSubmission extends JApplet {
    private final static String FORM_TEXT = "<html><head></head><body><h1>Formulario</h1>"
    + "<form action=\"\" method=\"get\"><table><tr><td>Nombre:</td>"
    + "<td><input name=\"Nombre\" type=\"text\" value=\"James T.\"></td>"
    + "</tr><tr><td>Apellido:</td>"
    + "<td><input name=\"Apellido\" type=\"text\" value=\"Kirk\"></td>"
    + "</tr><tr><td>Cargo:</td>"
    + "<td><select name=\"Cargo\"><option>Captain<option>Comandante<option>General</select></td>"
    + "</tr><td colspan=\"2\" align=\"center\"><input type=\"submit\" value=\"Enviar\"></td>"
    + "</tr></table></form></body></html>";
    protected HashMap radioGroups = new HashMap();
    private Vector v = new Vector();
    public FormSubmission() {
    getContentPane().setLayout(new BorderLayout());
    JEditorPane editorPane = new JEditorPane();
    editorPane.setEditable(false);
    editorPane.setEditorKit(new HTMLEditorKit()
    public ViewFactory getViewFactory() {
    return new HTMLEditorKit.HTMLFactory() {
    public View create(Element elem) {
    Object o = elem.getAttributes().getAttribute(javax.swing.text.StyleConstants.NameAttribute);
    if (o instanceof HTML.Tag)
    HTML.Tag kind = (HTML.Tag) o;
    if (kind == HTML.Tag.INPUT || kind == HTML.Tag.SELECT || kind == HTML.Tag.TEXTAREA)
    return new FormView(elem)
    protected void submitData(String data)
    showData(data);
    protected void imageSubmit(String data)
    showData(data);
    // Workaround f�r Bug #4529702
    protected Component createComponent()
    if (getElement().getName().equals("input") &&
    getElement().getAttributes().getAttribute(HTML.Attribute.TYPE).equals("radio"))
    String name = (String) getElement().getAttributes().getAttribute(HTML.Attribute.NAME);
    if (radioGroups.get(name) == null)
    radioGroups.put(name, new ButtonGroup());
    ((JToggleButton.ToggleButtonModel) getElement().getAttributes().getAttribute(StyleConstants.ModelAttribute)).setGroup((ButtonGroup) radioGroups.get(name));
    JComponent comp = (JComponent) super.createComponent();
    // Peque�a mejora visual
    comp.setOpaque(false);
    return comp;
    return super.create(elem);
    //editorPane.setText(FORM_TEXT);
    editorPane.setText(texto);
    getContentPane().add(new JScrollPane(editorPane), BorderLayout.CENTER);
    private void showData(String data) {
         // ergebnis significa resultado
    StringBuffer ergebnis = new StringBuffer("");
    StringTokenizer st = new StringTokenizer(data, "&");
    while (st.hasMoreTokens()) {
    String token = st.nextToken();
    String key = URLDecoder.decode(token.substring(0, token.indexOf("=")));
    String value = URLDecoder.decode(token.substring(token.indexOf("=")+1,token.length()));
    v.add(value);
    ergebnis.append(" "); ergebnis.append(key); ergebnis.append(": "); ergebnis.append(value); ergebnis.append(" ");
    ergebnis.append(" ");
    JOptionPane.showMessageDialog(this, ergebnis.toString());
    public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame ();
    FormSubmission editor = new FormSubmission ();
    frame.getContentPane().add(editor);
    frame.pack();
    frame.show();
    }

  • Carriage Returns and Tabs in XML element

    I have a number of carriage returns and tabs within an xml element. When I take that element I would like it to transform to html in which I am then displaying within a JEditorPane. However, when I do this it is one long string. I have tried the xml:space="preserve" within that element and this still is not working.
    Here is part of the xml with the carriage return line feeds. The element that I am talking about is called pseudocode. You can see it is displayed correctly below.
    Design Document XML : <?xml version="1.0" encoding="ISO-8859-1"?><design-doc><title-page><title>Testing Document</title><class-prepared-for>Lloyd</class-prepared-for><authors>Ben Garbers</authors><date-created>September 23, 2004</date-created></title-page><introduction text="This is the introduction. This is the introduction."/><class-definitions><class-definition class-name="ClassOne" visibility="public" class-complexity="not complex"><global-variables><variable visibility="public" name="VariableOne" object="String" comments="This is a String."/><variable visibility="public" name="VariableTwo" object="Integer" comments="This is an Integer."/></global-variables><methods><method name="MethodOne" synopsis="This will do some things." purpose="public" visibility="public"><input-parms><variable visibility="null" name="firstName" object="String" comments="null"/></input-parms><output-parms><variable visibility="null" name="lastName" object="String" comments="null"/></output-parms><local-variables><variable visibility="null" name="age" object="int" comments="null"/></local-variables><pseudocode xml:space="preserve">/* Ensure that player name exist in the system*/
    if (player =null)
         NullPlayerException;
              if (NOT (isPlayerNameExist(player)))
                   throw PlayerNameNotExistException;
              /* Ensure player name exist in the team already*/
              i ? 1;
              while (i <= length(mPlayers)) {
                   if (mPlayers.mPlayerName != playerName)
                        throw PlayerNameNotExistInTeamException;
    this.mPlayers ? this.mPlayers - player;</pseudocode>
    However, when I do the transformation I get the following with the pseudocode:
    /* Ensure that player name exist in the system*/if (player =null)     NullPlayerException;          if (NOT (isPlayerNameExist(player)))               throw PlayerNameNotExistException;          /* Ensure player name exist in the team already*/          i ? 1;          while (i <= length(mPlayers)) {               if (mPlayers[i].mPlayerName != playerName)                    throw PlayerNameNotExistInTeamException;}this.mPlayers ? this.mPlayers - player;
    It looks like it adds some spaces but no carriage returns or line feeds.
    My transformation code is the following:
         public ParseFile(String xmlString) {
              try {
              //Here we will load the correct style sheet for the message
              //that will be formatted.
              String urlString = "DesignDocument.xsl";
              URL url = this.getClass().getResource(urlString);
              System.out.println("URL to style sheet = " + url.toString());
              String styleSheetName = url.getFile();
              System.out.println("Style sheet name : " + styleSheetName);
              InputStream styleSheetInputStream = this.getClass().getResourceAsStream(urlString);
              //We will than load our SAXParerFactory and parse the message.
              SAXParserFactory SPFactory = SAXParserFactory.newInstance();
              SPFactory.setValidating(true);
              SAXParser sp = SPFactory.newSAXParser();
              XMLReader sax2parser = sp.getXMLReader();
              //NO Validation done on for this because we do NOT have a DTD.
              sax2parser.setFeature(
                   "http://xml.org/sax/features/validation",
                   false);
              sax2parser.setContentHandler(new FileContentHandler());
              //we create a character array of the length of the xml message String
              char[] messageCharacterArray =
                   new char[xmlString.length()];
              // we then put the xml string into the character array.
              messageCharacterArray = xmlString.toCharArray();
              // after this ew end up creating a CharArrayReader that will be used by the Sax
              // parser to parse the xml.
              CharArrayReader xmlCharArrayReader =
                   new CharArrayReader(messageCharacterArray);
              // we put the xml character array within the Input Source which will then be parsed
              // by the Sax2 parser.
              InputSource in = new InputSource(xmlCharArrayReader);
              // Use a Transformer for outputting the message into our formatted xml using
              // the stylesheet defined up in a messages own sxl stylesheet file.
              TransformerFactory tFactory = TransformerFactory.newInstance();
              tFactory.setURIResolver(new BasicURIResolver());
              StreamSource stylesource = new StreamSource(styleSheetInputStream);
              Transformer transformer = tFactory.newTransformer(stylesource);
    //          transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    //          transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    //          Properties properties = new Properties();
    //          properties.setProperty("indent", "yes");
    //          properties.setProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    //          transformer.setOutputProperties(properties);
              // We will use a ByteArrayOutputStream to put our transformed xml.
              ByteArrayOutputStream bos = new ByteArrayOutputStream();
              StreamResult result = new StreamResult(bos);
              SAXSource source = new SAXSource(in);
              transformer.transform(source, result);
              String s = bos.toString();
              StringBuffer sb = new StringBuffer();
              //This will make sure the Version Line is not shown.
              BufferedReader br = new BufferedReader(new StringReader(s));
              String line = "";
              while ((line = br.readLine()) != null) {
                        sb.append(line);
              bos.close();
              br.close();
              formattedXmlString = sb.toString();
              System.out.println("--------------------------------");
              System.out.println(formattedXmlString);
              System.out.println("--------------------------------");
              } catch (Exception e) {
                   e.printStackTrace();
    I have been searching and trying to figure this out forever. Any help would be greatly appreciated. Bottom line is that I want carriage returns and tabs to work when transferring from the xml to xsl.

    I get the following line when adding the <pre> tags.
    /* Ensure that player name exist in the system*/if (player =null)     NullPlayerException;          if (NOT (isPlayerNameExist(player)))               throw PlayerNameNotExistException;          /* Ensure player name exist in the team already*/          i ? 1;          while (i <= length(mPlayers)) {               if (mPlayers[i].mPlayerName != playerName)                    throw PlayerNameNotExistInTeamException;}this.mPlayers ? this.mPlayers - player;
    On the screen this is shown on 1 line. It looks like the tabs are working correctly. However, the carriage return, line feeds do not seem to be working. The xml that is pushed into the transformation has the carriage returns and line feeds and is formatted correctly. There has to be something happening when the xsl takes the xml String. When I add <BR></BR> within the xml that doesn't seem to work either.
    I am really sumpted. If you could help DrClap I would really be appreciated.

  • Loading XML Document from JFileChooser

    My initial version of this app I hardcoded the XML filename. Now, I would like to load an xml file via a JFileChooser. The problem I'm having is that I create the DOM Document in the constructor because of dependencies on the JTree. Well, I don't call showDialog until the "open" action is called which is further into the program. By then it's too late. Here is the code. I extracted some unecessary code for reading purposes.
    public class DomGui extends JPanel implements DomGuiConstants, ActionListener
        private JScrollPane treeView;
        private String xmlFilename;
        private Document document;
        private JFileChooser fileChooser;
        private ExtensionFilter fileFilter;
        private static JFrame frame;
        private static JTree jtree;
        public DomGui() throws Exception
            frame = new JFrame(DOM_VIEWER);
            fileChooser = new JFileChooser();
            fileFilter = new ExtensionFilter(XML_EXTENSION, XML_DESCRIPTION);
            // Create the Document
            //xmlFilename = "W:/RoseModel/ImplementationView/seng/ewcs/clwc/Simulation/Utilities/Xml/DomViewer/TVschedule.xml";
            try
                CreateDomDocument createDomDocument = new CreateDomDocument(xmlFilename);
                document = createDomDocument.getDocument();
            catch (FileNotFoundException fnfe)
                System.out.println(fnfe);
                System.exit(1);
            // Create a Tree Model
            DomTreeModel model = new DomTreeModel(document);
            // Create a renderer
            DomTreeCellRenderer  treeCellRenderer = new DomTreeCellRenderer();
            // Create the JTree
            jtree = new JTree(model);
            // Create an Editor
            DomTreeCellEditor treeCellEditor = new DomTreeCellEditor(jtree);
            // Build left-side view
            // an empty tree and put it a JScrollPane so users can see
            // its contents as it gets large
            treeView = new JScrollPane(jtree);
            treeView.getViewport().add(jtree);
            treeView.setPreferredSize(new Dimension( leftWidth, windowHeight ));
            // Create a JSplitPane to hold the left side JTree
            // and the right side JEditorPane
            // Build split-pane view
            splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
                                                       treeView,
                                                       htmlView );
            splitPane.setContinuousLayout( true );
            splitPane.setDividerLocation( leftWidth );
            splitPane.setPreferredSize(new Dimension
                                                        ( windowWidth + 10, windowHeight+10 ));
            // Add GUI components
            this.setLayout(new BorderLayout());
            this.add("Center", splitPane );
        public static void makeFrame()
            int FRAME_WIDTH = 670;
            int FRAME_HEIGHT = 600;
            // Set up the tree, the views, and display it all
            try
                final DomGui guiPanel = new DomGui();
                frame.getContentPane().add("Center", guiPanel );
            catch (Throwable throwable)
                throwable.printStackTrace();
                System.exit(1);
        public void actionPerformed(ActionEvent actionEvent)
            String actionCommand = actionEvent.getActionCommand();
            System.out.println("Action: " + actionCommand);
            if (actionCommand.equalsIgnoreCase("Quit"))
                System.exit(0);
            else if (actionCommand.equalsIgnoreCase("Open"))
                showDialog("Open XML File",
                                 "Open",
                                 "Open the file",
                                 'o',
                                 null);
        // end actionPerformed
        public File showDialog (String dialogTitle,
                                            String approveButtonText,
                                            String approveButtonToolTip,
                                            char approveButtonMnemonic,
                                            File file)
            fileChooser.setDialogTitle(dialogTitle);
            fileChooser.setApproveButtonText(approveButtonText);
            fileChooser.setApproveButtonToolTipText(approveButtonToolTip);
            fileChooser.setApproveButtonMnemonic(approveButtonMnemonic);
            fileChooser.setFileSelectionMode(fileChooser.FILES_ONLY);
            fileChooser.rescanCurrentDirectory();
            fileChooser.setSelectedFile(file);
            fileChooser.addChoosableFileFilter(fileFilter);
            fileChooser.setFileFilter(fileFilter);
            int result = fileChooser.showDialog(this, null);
            System.out.println("Result is: " +result);
            if (result == fileChooser.APPROVE_OPTION)
                System.out.println("I'm Here 1");
                System.out.println("File selected: " + fileChooser.getSelectedFile());
                xmlFilename = fileChooser.getSelectedFile().toString();
                return fileChooser.getSelectedFile();
            else
                System.out.println("I'm Here 2");
                return null;
        // end showDialog
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    In your actionPerformed() method, shouldn't you do something with the File returned by showDialog()? For instance:
            else if (actionCommand.equalsIgnoreCase("Open"))
                xmlFilename = showDialog("Open XML File",
                                 "Open",
                                "Open the file",
                                'o',
                                 null).getName();
            }Because it seems that, for now at least, you're choosing a file and then just kinda throwing it away...

  • How to use CSS in JEditorPane?

    I want to dispalay a XML file in JEditorPane with CSS. I have do the following:
    StyleSheet stylesheet=new StyleSheet();
    FileReader in=new FileReader(cssFileName);
    stylesheet.loadRules(in,null);
    HTMLEditorKit kit=(HTMLEditorKit)ShowPane.getEditorKitForContentType("text/html");
    kit.setStyleSheet(stylesheet);
    ShowPane.setEditorKit(kit);
    ShowPane.setPage(this.getClass().getResource(xmlFileName));
    But the stylesheet seems have no effect on the output of the JEditorPane-ShowPane.why?

    JEditorPane with StyleSheets, CSS, is partially supported by Java 2, on level 1, but not perfect. To load it, you should invoke it's loadRules method, passing it a Reader corresponding to the StyleSheet file, using the method : public void loadRules(Reader in, URL ref) throws IOException

  • Using a CSS in a JEditorPane

    I'm trying to display html pages inside of a JEditorPane using a CSS. I've got some lines of code but I'm not sure which are needed. Here's what I have.
    htmlPane.setEditable(false);
         htmlPane.setContentType("text/html");
         HTMLEditorKit kit = new HTMLEditorKit();
         kit.setStyleSheet(getStyles());
    HTMLDocument htmlDoc = (HTMLDocument)kit.createDefaultDocument();
         htmlPane.setEditorKit(kit);
         htmlPane.setDocument(htmlDoc);
    getStyles() points to my .css file.
    Now how do I display the page? Do I use htmlPane.setPage(), setText(), read(), or something else? If i'm supposed to use htmlDoc how do I add content to that?
    I need to display an xml file formatted nicely without the tags. Any help or advice would be greatly appreciated.
    Thanks

    Hi Elad,
    For JSPs to access this css file here is the sample code. Make sure that you keep your css file inside dist->css folder.
    <Html>
    <Head>
    <%@ page import="com.sapportals.portal.prt.component.IPortalComponentResponse"%>
    <%@ page import="com.sapportals.portal.prt.resource.IResource"%>
    <%
    IPortalComponentResponse componentResponse =
        (IPortalComponentResponse)pageContext.getAttribute(javax.servlet.jsp.PageContext.RESPONSE);
    IResource suckerfishCss = componentRequest.getResource(IResource.CSS, "css/GlobalReportStyles.css");
    componentResponse.include(componentRequest, suckerfishCss);
    %>
    </Head>
    <body>
    </body>
    </html>
    Now the class files must be availble to you.
    Regards,
    Vishal

Maybe you are looking for