SetPage in JEditorPane....

I try to display a html file in my local system by
try{
     URL url=new URL("http","localhost","E:/users/project/smart[1].html");
     EditorP.setContentType("text/html");
     EditorP.setPage(url);
    }catch(Exception e){System.out.println(e);}and I get the following exception
java.net.ConnectException: Connection refused: no further informationany help is greatly appriciable.
Cheers
Sasi

Hi! :)
But it failed to detects folders.I directly placed my html file in E:It failed to detect the forlders because you probably used '\' instead of '/'. This is a common mistake when people use the URL class.
URL uses only '/' as file separator. It's easy to remember though. I bet you've never seen any web site like "http://www.yahoo.com\index.html" right? :)
CUL8er,
Nick.

Similar Messages

  • Calling setPage of JEditorPane from behind proxy

    hi
    I have a peculiar problem...
    I am trying to make a small tool....a small java browser kind of a thing...
    I am behind a proxy and so when I call setPage on the jeditorpane it gives 407 error ie.Proxy authentication required.
    Now I know how to do it through a URLConnection by setting the Reuest property...But how to do it in this case....
    Just putting http.proxyUser and http.proxyPassword in System properties is not working...
    Please help

    TRY WITH java.net API
    THERE ARE SOME METHODS TO WORK WITH PROXIES.
    HOW EVER YOU SHOULD NEED AUTHRIZATION LEVEL TO GO OVER YOUR PROXY SERVER.
    MEANS YOU SHOULD HAVE A PASSWORD

  • JEditorPane setpage() problems

    Hi all!!
    I am developing a SWING application wich consists of a JFrame that contains a splitpane with a JTree on the left side and a JPanel with a cardlayout on the right one.
    Once the user navigates through the tree on the left different cards get loaded on the right panel.
    My problem is that when I show the card where a JEditorPane is located and use the setPage(url) to modify the document to be shown nothing happens, meaning that it doesn�t change the document that is displayed (the one URL that I passed on creating the JEditorPane). I mean, the card gets loaded, and I have confirmed that the URL that I pass exists and I pass different ones as well, but nothing seems to happen and the document remains the same.
    Please, can you give me any hints of why this is happening? Can I repaint the card or something??
    Is there any relationship between the CardLayout and the unability to setPage the JEditorPane.
    Please Help!!
    Here is the code:

    I've had this Problem when I was building a HTML-Editor-Applet.
    The Problem was, that there was a Style-Attribute like e.g. text-decoration:underlined. If I removed the underlined style the Attribut was text-decoration:none, but the getText() method just cared about the Style with the name text-decoration to handle this Element as underlined. I had to build my own getText() method by examing all the Elemntes from the Document and set the html-Tags for the style-attributes.
    Jörn

  • Fade a JEditorPane

    Hi,
    I've been struggling with this problem for days now. I'm displaying HTML pages in an JEditorPane so that I can control the content from my webapp. The JEditorPane is placed in a JPanel (called mainpanel) togheter with another JPanel (with some buttons which I call toppanel). I place the TopPanel at the top of the MainPanel and the JEditorPane in the bottom (so the TopPanel becomes like a menu). I then use setPage on the JEditorPane to switch the different views (HTML pages).
    What I would like to do when I change the HTML page is to fade the JEditorPane. For example
    public void changePage(String url)
    JEditorPane.fadeOut(); <----DONT KNOW HOW TO DO THIS
    JEditorPane.setPage(url);
    JEditorPane.fadeIn(); <----DONT KNOW HOW TO DO THIS
    The fade should be done without affecting the TopPanel.
    Ive tried different solutions to do this:
    1. Using GlassPane - but I could get it to work.
    2. Using a javabrowser and then run javascript to fade. This didn't work because of license issues and because how it was designed (I have thread changing the content and that was not allowed)
    Could someone help in simply fading in and out the EditorPane itself.
    BR, Jake

    JAKE142 wrote:
    ..Could you please give me a code sample?
    Can u gimme da codez? (1)
    How about you give us a 'code sample' of your best effort of implementing the suggestion? Note also:
    - For better help sooner, post an SSCCE.
    - When posting code, code snippets, HTML/XML or input/output, please use the code tags. The code tags protect the indentation and formatting of the sample.
    - Be very specific about what you saw in the current code, and what you expected or hoped to see.
    ..I think I tried it but without success.1) You did succeed in sounding pathetic. As an aside, that will get you less help, not more.

  • Student in distress: Read data from text file to fill a JTable

    I'm already late 2 weeks for my project and I still can't figure this out :(
    The project is made of 3 classes; the main one is Viewer.java; it creates the interface, Menu.java that manages the menu and the methods related to it and finally JTableData.java that extends JTable ( This is the part that I don't really understand)
    In the class MENU.JAVA I wrote the method jMenuOpen_actionPerformed(...) for the button OUVRIR (Open) that let's me select the file to read, then puts the content in a 2D table. Here' s my problem: I have to somehow update the content of the table created in VIEWER.JAVA with the content read from the file (cvs file delimited by ";") using a JTableData object (?)
    //THIS IS THE FIRST CLASS VIEWER.JAVA THAT CONTAINS THE MAIN METHOD
    //AND CREATES THE INTERFACE
    package viewer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Viewer extends JFrame {
      public Menu menu = null;
      GridLayout gridLayout1 = new GridLayout();
      JTabbedPane jTabbedPane = new JTabbedPane();             
      JTableData jTableInfo = new JTableData(30, 7);
      public Viewer() {
              addWindowListener(new WindowAdapter()
              {               public void windowClosing(WindowEvent e)
                        dispose();
                        System.exit(0);
            try 
                jbInit();
                this.setSize(1000, 700);
                this.setVisible(true);
            catch(Exception e)
                e.printStackTrace();
      public static void main(String[] args) {
          Viewer viewer = new Viewer();
      private void jbInit() throws Exception {
        menu = new Menu(this);
        gridLayout1.setColumns(1);
        this.setTitle("Viewer");
        this.getContentPane().setLayout(gridLayout1);
        jTableInfo.setMaximumSize(new Dimension(0, 64));
        jTableInfo.setPreferredSize(new Dimension(0, 64));
        //TO DO Partie de droite
        JTabbedPane webViewerTabs = new JTabbedPane();
        //972 3299
        //java.net.URL URL1 = new java.net.URL("http://www.nba.com");
        //java.net.URL URL2 = new java.net.URL("http://www.insidehoops.com");
        //java.net.URL URL3 = new java.net.URL("http://www.cnn.com");
        JEditorPane webViewer01 = new JEditorPane();
        webViewer01.setEditable(false);
        //webViewer01.setPage(URL1);
        JEditorPane webViewer02 = new JEditorPane();
        webViewer02.setEditable(false);
        //webViewer02.setPage(URL2);
        JEditorPane webViewer03 = new JEditorPane();
        webViewer03.setEditable(false);
        //webViewer03.setPage(URL3);
        webViewerTabs.addTab("Site01", webViewer01);
        webViewerTabs.addTab("Site02", webViewer02);
        webViewerTabs.addTab("Site03", webViewer03);
        jTabbedPane.add(webViewerTabs);
            //End TO DO   
        this.getContentPane().add(jTableInfo);
        this.getContentPane().add(jTabbedPane);
        this.setJMenuBar(menu);  
    //This is the MENU.JAVA CLASS WHERE I OPEN THE FILE, READ THE
    //CONTENT AND WHERE I SHOULD SEND THE DATA TO THE TABLE.
    //Title:        Menu
    //Author:       Luc Duong
    package viewer;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    public class Menu extends JMenuBar {
      JMenu jMenu1 = new JMenu();
      JMenuItem jMenuNew = new JMenuItem();
      JMenuItem jMenuOpen = new JMenuItem();
      JMenuItem jMenuSave = new JMenuItem();
      JMenuItem jMenuExit = new JMenuItem();
      JMenuItem jMenuApropos = new JMenuItem();
      JFileChooser fileChooser = new JFileChooser();
      Viewer viewer = null;
      boolean isFileChanged = false;
      private File fileName;
      static String data [][] = new String[7][9];
      public int lineCount;
      public Menu(Viewer viewer) {
        try  {
          jbInit();
          this.viewer = viewer;
          this.add(jMenu1);
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jMenu1.setText("Fichier");
        jMenuNew.setText("Nouveau");
        jMenuNew.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuNew_actionPerformed(e);
        jMenuOpen.setText("Ouvrir");
        jMenuOpen.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuOpen_actionPerformed(e);
        jMenuSave.setText("Sauvegarder");
        jMenuSave.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuSave_actionPerformed(e);
        jMenuExit.setText("Quitter");
        jMenuExit.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuExit_actionPerformed(e);
        jMenuApropos.setText("A propos");
        jMenuApropos.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            jMenuApropos_actionPerformed(e);
        jMenu1.add(jMenuNew);
        jMenu1.add(jMenuOpen);
        jMenu1.add(jMenuSave);
        jMenu1.add(jMenuExit);       
        jMenu1.add(jMenuApropos);   
      void jMenuNew_actionPerformed(ActionEvent e) {
      //THIS IS THE METHOD I'M WORKING ON RIGHT NOW
      void jMenuOpen_actionPerformed(ActionEvent e) {
          fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
          int result = fileChooser.showOpenDialog(this);
          if (result == JFileChooser.CANCEL_OPTION) return;
          if (result == JFileChooser.APPROVE_OPTION)
              //[email protected]
              File chosenFile = fileChooser.getSelectedFile();
              String path = chosenFile.getPath();
              String nom = chosenFile.getName();
              boolean exist = chosenFile.exists();
              try
                FileReader fr = new FileReader(chosenFile);
                BufferedReader reader = new BufferedReader(fr);
                System.out.println("Opening File Successful!" + chosenFile.getName());
                //String  qui contient la ligne courante
                String currentLine = new String();
                StringTokenizer currentLineTokens = new StringTokenizer("");
                int row = 0;
                int column = 0;
                while( (currentLine = reader.readLine() ) != null)
                    currentLineTokens = new StringTokenizer(currentLine,";");
                    System.out.println("Now reading line index: " + row);
                    while(currentLineTokens.hasMoreTokens())
                        data[row][column] = currentLineTokens.nextToken();
                        System.out.println(column + "\t" + data[row][column]);
                        if(column>=8) column=-1;
                        column++;
                    row++;
                lineCount = row-1;
                System.out.println("\nNombre total de lignes: " + lineCount);
            catch(Exception ex)
                System.out.println("Test: " + ex.getMessage());
                JOptionPane.showMessageDialog(this, "Erreur d'ouverture du fichier", "Erreur d'ouverture du fichier", JOptionPane.ERROR_MESSAGE);
      void jMenuSave_actionPerformed(ActionEvent e) {
          if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this))
                System.err.println("Save: " + fileChooser.getSelectedFile().getPath());     
      void jMenuExit_actionPerformed(ActionEvent e) {
        if (!isFileChanged)
           System.exit(1);
        else
            JOptionPane.showConfirmDialog(null, "Do you want to save now?", "Save?", JOptionPane.YES_NO_OPTION);
          // ask the user if he want to save
          // yes or no?
          // yes
           jMenuSave_actionPerformed(e);
          // no
          System.exit(1);
      void jMenuApropos_actionPerformed(ActionEvent e) {
    //THIS IS THE JTABLEDATA.JAVA CLASS THAT EXTENDS JTable. I'm not sure
    // how this works :(//Title: JTableData
    //Author: Luc Duong
    package viewer;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class JTableData extends JTable {
    public JTableData(int row, int col)
    super(row, col);

    Hi, Salut
    you should use JTable's DataModel to update your table.
    data[row][column] = currentLineTokens.nextToken();
    jTableInfo.getModel().setValueAt(data[row][column], row, column);
    jTableInfo.repaint();BEWARE CSV files and StringTokenizer, i've had problems with it (for example ;;Test; is not tokenized "", "", "Test")
    StringTokenizer ignores separator when in first position, and ignores double separators. I use this piece of code before tokenize a String :
    private static char _separator = ';';
    private static String checkCsvString(String s) {
             * V�rification du s�parateur inital, perdu par le StringTokenizer et
             * pourtant bien important
            if (s.startsWith("" + _separator)) {
                s = " " + s;
             * V�rification des doubles s�parateurs, perdus par le StringTokenizer
            int index;
            while ((index = s.indexOf("" + _separator + _separator)) >= 0) {
                s = s.substring(0, index) + _separator + " " + _separator + s.substring(index + 2);
            return s;
        }hope it helps
    Nico

  • Exceptions with JEditorPane setPage() method (Catching not possible)

    hi all
    if anyone can help me...please help
    I got serious exceptions with the JEditorPane()'s setPage() method
    I have written the try & catch still i could not catch the exception..(those exceptions are not displaying any of my program lines)..setPage() mehod was executed properly and the page was displyed on the editorpane..and then exceptions r coming..
    --------my code--------
    java.net.URL fileurl =LongTask.class.getResource(modifiedfilename);
    editorpane.setPage(fileurl);
    ---------------------exceptions
    java.lang.NullPointerException
    at java.util.Hashtable.put(Hashtable.java:393)
    at javax.swing.text.SimpleAttributeSet.addAttribute(SimpleAttributeSet.java:176)
    at javax.swing.text.html.CSS.translateHTMLToCSS(CSS.java:687)
    at javax.swing.text.html.StyleSheet.translateHTMLToCSS(StyleSheet.java:491)
    at javax.swing.text.html.StyleSheet$ViewAttributeSet.<init>(StyleSheet.java:2476)
    at javax.swing.text.html.StyleSheet.getViewAttributes(StyleSheet.java:312)
    at javax.swing.text.html.BlockView.getAttributes(BlockView.java:275)
    at javax.swing.text.html.StyleSheet$ViewAttributeSet.getResolveParent(StyleSheet.java:2609)
    at javax.swing.text.html.StyleSheet$ViewAttributeSet.doGetAttribute(StyleSheet.java:2589)
    at javax.swing.text.html.StyleSheet$ViewAttributeSet.getAttribute(StyleSheet.java:2569)
    at javax.swing.text.ParagraphView.setPropertiesFromAttributes(ParagraphView.java:105)
    at javax.swing.text.html.ParagraphView.setPropertiesFromAttributes(ParagraphView.java:87)
    at javax.swing.text.html.ParagraphView.setParent(ParagraphView.java:60)
    at javax.swing.text.CompositeView.replace(CompositeView.java:200)
    at javax.swing.text.BoxView.replace(BoxView.java:164)
    at javax.swing.text.CompositeView.loadChildren(CompositeView.java:97)
    at javax.swing.text.CompositeView.setParent(CompositeView.java:122)
    at javax.swing.text.html.BlockView.setParent(BlockView.java:55)
    at javax.swing.text.CompositeView.replace(CompositeView.java:200)
    at javax.swing.text.BoxView.replace(BoxView.java:164)
    at javax.swing.text.html.TableView$RowView.replace(TableView.java:1414)
    at javax.swing.text.CompositeView.loadChildren(CompositeView.java:97)
    at javax.swing.text.CompositeView.setParent(CompositeView.java:122)
    at javax.swing.text.CompositeView.replace(CompositeView.java:200)
    at javax.swing.text.BoxView.replace(BoxView.java:164)
    at javax.swing.text.html.TableView.replace(TableView.java:864)
    at javax.swing.text.CompositeView.loadChildren(CompositeView.java:97)
    at javax.swing.text.CompositeView.setParent(CompositeView.java:122)
    at javax.swing.text.html.TableView.setParent(TableView.java:768)
    at javax.swing.text.CompositeView.replace(CompositeView.java:200)
    at javax.swing.text.BoxView.replace(BoxView.java:164)
    at javax.swing.text.View.updateChildren(View.java:1126)
    at javax.swing.text.View.insertUpdate(View.java:710)
    at javax.swing.text.View.forwardUpdateToView(View.java:1217)
    at javax.swing.text.View.forwardUpdate(View.java:1192)
    at javax.swing.text.BoxView.forwardUpdate(BoxView.java:222)
    at javax.swing.text.View.insertUpdate(View.java:716)
    at javax.swing.plaf.basic.BasicTextUI$RootView.insertUpdate(BasicTextUI.java:1487)
    at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.insertUpdate(BasicTextUI.java:1726)
    at javax.swing.text.AbstractDocument.fireInsertUpdate(AbstractDocument.java:184)
    at javax.swing.text.DefaultStyledDocument.insert(DefaultStyledDocument.java:201)
    at javax.swing.text.html.HTMLDocument.insert(HTMLDocument.java:232)
    at javax.swing.text.html.HTMLDocument$HTMLReader.flushBuffer(HTMLDocument.java:3254)
    at javax.swing.text.html.HTMLDocument$HTMLReader.addContent(HTMLDocument.java:3196)
    at javax.swing.text.html.HTMLDocument$HTMLReader.blockClose(HTMLDocument.java:3128)
    at javax.swing.text.html.HTMLDocument$HTMLReader$BlockAction.end(HTMLDocument.java:2334)
    at javax.swing.text.html.HTMLDocument$HTMLReader.handleEndTag(HTMLDocument.java:2233)
    at javax.swing.text.html.parser.DocumentParser.handleEndTag(DocumentParser.java:217)
    at javax.swing.text.html.parser.Parser.parse(Parser.java:2072)
    at javax.swing.text.html.parser.DocumentParser.parse(DocumentParser.java:106)
    at javax.swing.text.html.parser.ParserDelegator.parse(ParserDelegator.java:78)
    at javax.swing.text.html.HTMLEditorKit.read(HTMLEditorKit.java:230)
    at javax.swing.JEditorPane.read(JEditorPane.java:504)
    at javax.swing.JEditorPane$PageLoader.run(JEditorPane.java:551)
    please share ideas to solve this problem

    But how can I cause GUI thread to run in my thread
    group? As I suppose GUI thread is started by JVM and
    is something separate from my code - I can get a
    reference to GUI thread but don't know how to
    manipulate or replace it...One alternative is to completely separate the GUI code from your code.
    Your code, which is wrapped in appropriate try/catch blocks, runs on its own thread and does its own processing. When it's done with that processing, it queues the results on the event thread for display. If an exception occurs during your processing, then you queue something that notifies the GUI.
    The simplest way to implement this is to spawn a new thread for each operation. The Runnable that you give to that thread looks like the following:
    public MyOperationClass implements Runnable
        public void run()
            try
                // do your exception-generating code here
                SwingUtilities.invokeLater( new MyGUIUpdateClass(param1, param2));
            catch (Exception e)
                SwingUtilities.invokeLater(new MyExceptionReporter(e));
    }This is only a bare-bones solution (and hasn't been compiled). Since it separates the GUI from actual processing, you'll probably want to display a wait cursor while the processing thread is doing its thing. You'll probably end up implementing a class that implements this pattern. You may also want to create a producer-consumer thread, so that the user won't invoke, say, a dozen different operations at once.
    However, this sort of code is absolutely essential to Swing programming. Most apps do extensive non-GUI processing, such as database queries. If you run such queries in the GUI thread, your GUI will freeze.
    Sun has named this pattern "SwingWorker", although I don't think they've fleshed it out very fully: http://java.sun.com/products/jfc/tsc/articles/threads/threads2.html

  • JEditorPane, setPage and EDT

    The setPage(URL url) method for JEditorPane creates a thread and then loads the URL specified. In our software we're using something to check if all work dealing with Swing components is being done on the EDT. The code for this can be found here:
    http://www.clientjava.com/blog/2004/08/20/1093059428000.html
    Anyway, it turns out that the setPage method is not doing its work on the EDT, which seems like a bug since modifying a component off the EDT can lead to problems. Anyone want to shed some light on this topic or tell me if there's anything that can be done about it? Thanks.

    I am using setPage(URL) method to display files selected from a fileTree.
    I am facing a file locking problem, because of the the PageLoader thread spawned by the setPage method.
    The file is locked temporarily some times and prevents other applications to edit it.
    Can anyone help me what should I do to solve this problem?

  • JEditorPane.setPage - detecting that asynchronous image loading is complete

    Hi,
    I'm using a JEditorPane to load and display an html page of a url by using
    setPage(String url) ... and I've added a progress bar to show the user that loading is still occuring.
    Currently i'm detecting that the page has finished loaded by listening for the property change event named "page", like this:
        this.viewEditorPane.addPropertyChangeListener(
          new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent event) {
              if (event.getPropertyName().equals("page")) {
                loadingProgressBar.setIndeterminate(false);
                System.out.println("... finished loading");
          });I appreciate that images are loaded asynchronously.
    So what I'm wondering is how I can detect that all these associated images have also completed loading?
    Thanks ... Dougall

    if you want to load images synchronously you can use like, (i got it from this forum only)
    public class SynchronousHTMLEditorKit extends HTMLEditorKit {
        public SynchronousHTMLEditorKit() {
        public ViewFactory getViewFactory() {
            return new SynchronousImageViewFactory(super.getViewFactory());
        static class SynchronousImageViewFactory implements ViewFactory {
            ViewFactory impl;
            SynchronousImageViewFactory(ViewFactory impl) {
                this.impl = impl;
            public View create(Element elem) {
                View v = impl.create(elem);
                if((v != null) && (v instanceof ImageView)) {
                    ((ImageView)v).setLoadsSynchronously(true);
                return v;
    }

  • Problem using the setPage(String url) of JEditorPane

    Hi all !
    I'm developping a text file generator which generates a text file and use a viewer to display the content of this text file.
    The first time, it works correctly, it displays the text file content but the others times it doesn't work correctly, the first text file content remains displayed.
    It seems that the setpage(String url) method doesn't work correctly.
    Does anyone know this problem ?
    In advance, thanks a lot.
    Best regards,
    Farid.
    Here is the code of the viewer:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.lang.*;
    public class ViewerQCM extends JPanel {
         private JPanel panelSouth;
         private JLabel titreLabel;
         private JButton genererQCMButton;
         private JEditorPane editorPane;
         private JScrollPane scrollPane;
         public ViewerQCM() {
              JFrame frame = new JFrame("G�n�rateur de QCM");
              setLayout(new BorderLayout());
              panelSouth = new JPanel();
              panelSouth.setLayout(new FlowLayout());
    titreLabel = new JLabel("G�n�rateur de QCM", SwingConstants.CENTER);
              editorPane = new JEditorPane();
              editorPane.setContentType("text/plain");
    editorPane.setText("Cliquer sur le bouton \" G�n�rer QCM \" ");
              editorPane.setEditable(false);
              genererQCMButton = new JButton("G�n�rer QCM");
              genererQCMButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
              GenerateurDeQCM.getInstance().init();
              GenerateurDeQCM.getInstance().generateQuestionnaire();
                        try {
    editorPane.setPage("file:" + AccesBase.getString("generateur.QCM"));
                        catch (IOException ex) {
                             ex.printStackTrace();
    LogFile.getInstance().write("Exception *** IOException caught in constructor ViewerQCM() ***");
                   LogFile.getInstance().write(ex.getMessage());
                   LogFile.getInstance().flush();
              scrollPane = new JScrollPane(editorPane);
              add(titreLabel, BorderLayout.NORTH);
              add(scrollPane, BorderLayout.CENTER);
              panelSouth.add(genererQCMButton);
              add(panelSouth, BorderLayout.SOUTH);
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.getContentPane().add(this);
    frame.pack();
    frame.setSize(500,600);
    frame.setVisible(true);
         public static void main(String args[]) {
              new ViewerQCM();
    }

    hi,
    there is some problem with JedtorPane when you update the page. Image or not updated all the time because the buffer keep the old image and does not update it. The problem is that class got to much protected field so you cannot change nothing. It is a bug since Two years and no body as correct it.

  • JEditorPane - setPage

    How does one interrupt the loading of a HTML page in setPage of a JEditorPane? Have a situtation where clicking on different URL's should
    stop the loading of the previous page...
    Thanks
    Abraham Khalil

    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)", that demonstrates the incorrect behaviour.
    http://homepage1.nifty.com/algafield/sscce.html
    Don't forget to use the "Code Formatting Tags", so the posted code retains its original formatting.
    http://forum.java.sun.com/help.jspa?sec=formatting

  • JEditorPane.setPage halting other threads

    I'm in the process of creating a program which loads a html-file while I'm running another process at the same time. It seems like setPage halts my process after a short while.
    As an example I slightly altered a piece from a tutorial (http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JEditorPane.html)
    to include a button which is counted down with the help of a timer. As you can see, it's halted for about a second or so after a short while.
    Is there any way I can keep the countdown going fluently?
    import javax.swing.*;
    import javax.swing.event.*;
    //import com.inbis.invitt.SimpleBrowser.ButtonDelayer;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Browser extends JFrame implements HyperlinkListener, ActionListener {
    private JButton homeButton;
    private JTextField urlField;
    private JEditorPane htmlPane;
    private String initialURL;
    private Timer timer;
    public Browser(String initialURL) {
    super("Simple Swing Browser");
    this.initialURL = initialURL;
    addWindowListener(new WindowListener() {
    public void windowActivated(WindowEvent e) {
    public void windowClosed(WindowEvent e) {
    System.exit(0);
    public void windowClosing(WindowEvent e) {
    public void windowDeactivated(WindowEvent e) {
    public void windowDeiconified(WindowEvent e) {
    public void windowIconified(WindowEvent e) {
    public void windowOpened(WindowEvent e) {
    JPanel topPanel = new JPanel();
    topPanel.setBackground(Color.lightGray);
    homeButton = new JButton("Home");
    countdownButton(homeButton, 100, 100);
    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);
    public static void main(String[] args) {
    new Browser("http://www.sun.com/");
    public void countdownButton(JButton button, int delayMs, int delaysToPass) {
    ButtonDecreaser buttonDecreaser = new ButtonDecreaser(button, delaysToPass);
    timer = new Timer(delayMs, buttonDecreaser);
    timer.setInitialDelay(0);
    timer.start();
    private class ButtonDecreaser implements ActionListener {
    private int delayAmount;
    private JButton button;
    public ButtonDecreaser(JButton button, int delayAmount) {
    this.delayAmount = delayAmount;
    this.button = button;
    public void actionPerformed(ActionEvent evt) {
    if (delayAmount > 0) {
    button.setText(Integer.toString(delayAmount));
    } else {
    button.setText("Finished");
    timer.stop();
    delayAmount--;
    }

    Thank you very much for the replies so far. :)
    I am currently on a machine with duo-core, but I'd like to make my program compatible with the ones with single as well anyways. I guess I could find a way to have the processes run sequentially instead of parallely, but it would be really neat if I could get it working as I've intended. :)
    As for the code: sorry, my bad. Just tried to edit my original post without any luck. Here it is in proper format:
    import javax.swing.*;
    import javax.swing.event.*;
    //import com.inbis.invitt.SimpleBrowser.ButtonDelayer;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    public class Browser extends JFrame implements HyperlinkListener, ActionListener {
      private JButton homeButton;
      private JTextField urlField;
      private JEditorPane htmlPane;
      private String initialURL;
      private Timer timer;
      public Browser(String initialURL) {
        super("Simple Swing Browser");
        this.initialURL = initialURL;
        addWindowListener(new WindowListener() {
          public void windowActivated(WindowEvent e) {
          public void windowClosed(WindowEvent e) {
            System.exit(0);
          public void windowClosing(WindowEvent e) {
          public void windowDeactivated(WindowEvent e) {
          public void windowDeiconified(WindowEvent e) {
          public void windowIconified(WindowEvent e) {
          public void windowOpened(WindowEvent e) {
        JPanel topPanel = new JPanel();
        topPanel.setBackground(Color.lightGray);
        homeButton = new JButton("Home");
        countdownButton(homeButton, 100, 100);
        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);
      public static void main(String[] args) {
        new Browser("http://www.sun.com/");
      public void countdownButton(JButton button, int delayMs, int delaysToPass) {
        ButtonDecreaser buttonDecreaser = new ButtonDecreaser(button, delaysToPass);
        timer = new Timer(delayMs, buttonDecreaser);
        timer.setInitialDelay(0);
        timer.start();
      private class ButtonDecreaser implements ActionListener {
        private int delayAmount;
        private JButton button;
        public ButtonDecreaser(JButton button, int delayAmount) {
          this.delayAmount = delayAmount;
          this.button = button;
        public void actionPerformed(ActionEvent evt) {
          if (delayAmount > 0) {
            button.setText(Integer.toString(delayAmount));
          } else {
            button.setText("Finished");
            timer.stop();
          delayAmount--;
    }

  • JEditorPane.setPage(URL url), then I want to clean up HTML, how?

    According to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4695909
    the problem with the inconsistent ArrayIndexOutOfBoundsException that
    I have been getting whenever I would go to a particular URL to put
    into JEditorPane using setPage() - this may also be due to JEditorPane
    containing HTML which contains a <META> tag and/or <!-- comment tag --
    . I created a class SimpleHTMLRenderableEditorPane which extendsJEditorPane, based upon code I found in the aformentioned bug link
    which should auto-strip out "bad tags":
    * SimpleHTMLRenderableEditorPane.java
    * Created on March 13, 2007, 3:39 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ppowell.tools.ObjectTools.SwingTools;
    import javax.swing.JEditorPane;
    * A safer version of {@link javax.swing.JEditorPane}
    * @author Phil Powell
    * @version JDK 1.6.0
    public class SimpleHTMLRenderableEditorPane extends JEditorPane {
        //--------------------------- --* CONSTRUCTORS *--
        // <editor-fold defaultstate="collapsed" desc=" Constructors
    ">
        /** Creates a new instance of SimpleHTMLRenderableEditorPane */
        public SimpleHTMLRenderableEditorPane() {
            super();
        // </editor-fold>
        //----------------------- --* GETTER/SETTER METHODS *--
        // <editor-fold defaultstate="collapsed" desc=" Getter/Setter
    Methods ">
         * Overloaded to fix HTML rendering bug Bug ID: 4695909.
         * @param text
        public void setText(String text) {
            // Workaround for bug Bug ID: 4695909 in java 1.4
            // JEditorPane does not handle the META tag in the html HEAD
            if (isJava14() && "text/
    html".equalsIgnoreCase(getContentType())) {
                text = stripMetaTag(text);
            super.setText(text);
        // </editor-fold>
        //--------------------------- --* OTHER METHODS *--
        // <editor-fold defaultstate="collapsed" desc=" Methods ">
         * Clean HTML to remove things like <script>, <style>, <object>,
    <embed>, and <!-- -->
         * Based upon <a href="http://bugs.sun.com/bugdatabase/view_bug.do?
    bug_id=4695909">bug report</a>
        public void cleanHTML() {
            try {
                String html = getText();
                if (html != null && !html.equals("")) {
                    String[] patternArray = {
                        "<script[^>]*>[^<]*(</script>)?",
                        "<style[^>]*>[^<]*(</style>)?>",
                        "<object[^>]*>[^<]*(</object>)?>",
                        "<embed[^>]*>[^<]*(</embed>)?>",
                        "<!\\-\\-.*\\-\\->"
                    for (int i = 0; i < patternArray.length; i++) {
                        html = html.replaceAll(patternArray, "");
    setText(html);
    } catch (Exception e) {} // DO NOTHING
    * Determine if java version is 1.4.
    * @return true if java version is 1.4.x....
    private boolean isJava14() {
    String version = System.getProperty("java.version");
    return version.startsWith("1.4");
    * Workaround for Bug ID: 4695909 in java 1.4, fixed in 1.5
    * JEditorPane fails to display HTML BODY when META
    * tag included in HEAD section.
    * <html>
    * <head>
    * <META http-equiv="Content-Type" content="text/html;
    charset=UTF-8">
    * </head>
    * <body>
    * @param text html to strip.
    * @return same HTML text w/o the META tag.
    private String stripMetaTag(String text) {
    // String used for searching, comparison and indexing
    String textUpperCase = text.toUpperCase();
    int indexHead = textUpperCase.indexOf("<META ");
    int indexMeta = textUpperCase.indexOf("<META ");
    int indexBody = textUpperCase.indexOf("<BODY ");
    // Not found or meta not inside the head nothing to strip...
    if (indexMeta == -1 || indexMeta > indexHead && indexMeta <
    indexBody) {
    return text;
    // Find end of meta tag text.
    int indexHeadEnd = textUpperCase.indexOf(">", indexMeta);
    // Strip meta tag text
    return text.substring(0, indexMeta-1) +
    text.substring(indexHeadEnd+1);
    // </editor-fold>
    However, upon running the following line:
    SimpleBrowser.this.browser.cleanHTML();I spawn the following exception:
    Exception in thread "Thread-2" java.lang.RuntimeException: Must insert
    new content into body element-
            at javax.swing.text.html.HTMLDocument
    $HTMLReader.generateEndsSpecsForMidInsert(HTMLDocument.java:1961)
            at javax.swing.text.html.HTMLDocument
    $HTMLReader.<init>(HTMLDocument.java:1908)
            at javax.swing.text.html.HTMLDocument
    $HTMLReader.<init>(HTMLDocument.java:1782)
            at javax.swing.text.html.HTMLDocument
    $HTMLReader.<init>(HTMLDocument.java:1777)
            at
    javax.swing.text.html.HTMLDocument.getReader(HTMLDocument.java:137)
            at javax.swing.text.html.HTMLEditorKit.read(HTMLEditorKit.java:
    228)
            at javax.swing.JEditorPane.read(JEditorPane.java:556)
            at javax.swing.JEditorPane$PageLoader.run(JEditorPane.java:
    647)What should I do at this point?
    Thanks
    Phil

    Transfer all purchases from the iPad to iTunes on your computer, backup the iPad and then sync one last time.
    Then go to Settings>General>Reset>Erase all content and Settings to completely erase the iPad.
    Connect the new iPad to your computer and launch iTunes, restore from the backup of the old iPad and then sync with iTunes. You should be prompted to restore from the backup when you connect the new iPad to your computer's iTunes, but you can select it on your own as well.
    Transfer purchases.
    http://support.apple.com/kb/HT1848
    How to backup
    http://support.apple.com/kb/HT1766

  • JEditorPane - delay in setPage... (threads?)

    Mmmm....
    I've got the following code which "does something time consuming", hence I want to display a "loading" page whilst it does it....
    However, it seems that java only calls setPage at the end of the actionPerformed method. Hence file:///c:/temp/loading.html is shown once the action is complete! (and disappears as quickly as it appears because it is setPage is called again).
    Any ideas???
    JEditorPane htmlPane = new JEditorPane();
    JButton button = new JButton("Do something time consuming");
    button.addActionListener(new ActionListener()
       public void actionPerformed(ActionEvent evt)
          //attempt to display loading message
          try
             htmlPane.setPage("file:///c:/temp/loading.html");
          catch (IOException e)
             System.out.println(e.getMessage());
          //do something time consuming....
          for (int i = 0; i < 100000; i++)
             System.out.println(i);
          try
             htmlPane.setPage("file:///c:/temp/index.html");
          catch (IOException e)
             System.out.println(e.getMessage());
    }); Cheers,
    Ben

    Check out this thread for an explanation/solution:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=43592
    Exactly what I was looking for!!
    I had already searched the forums, but I guess its difficult to find what you are after if you don't know what you are looking for!! ;-)
    Cheers,
    Ben

  • JEditorPane.setPage() final  phase takes a while!!!

    Hi Java users,
    I'm displaying a document on a JEditorPane. I am using a SwingWorker to launch a thread that will accomplish the document load. However, there is a point when the SwingWorker has already finished his job (I now this since the finished() code has been executed), and it takes a few seconds more to display the document during which period I don't have any means to inform the user that all is in order and tell him to be patient. The JEditorPane shrinks to a tiny little white rectangle (almost a point) then -few sec. later- the document is shown. How can this issue be solved???
    Also, hard question, in spite of using the SwingWorker sometimes (withou any systematical pattern, randomly) the GUI "freezes". How is this possible?
    Thanks for your help in advance,
    Balint

    setPage already launches a separate thread to load
    the page; hence the method may return before the job
    is actually done: that terminates the SwingWorker
    construct. You control that via set/get
    getAsynchronousLoadPriority, which in turn use the
    AbstractDocument.AsyncLoadPriority priority: only if it
    not set (<0) the document will load synchronously.
    The GUI may freeze because it has less priority than
    needed. I use the following function   private static void lowerThreadPriority()
          Thread t = Thread.currentThread();
          int p = t.getPriority();
          if (p > Thread.MIN_PRIORITY)
             t.setPriority(p - 1);
       } to lower the priority of a SwingWorker, as they
    start with the same priority of the GUI.
    The GUI thread needs to gain read access to the document
    to update the display as new data is being loaded. So,
    it is important that the function that loads the doc
    does not lock it for writing for the whole process, if
    you want data to become visible before loading ends.

  • This method "setPage(url)" of JEditorPane do not support javascript

    does java have any package to support javascript

    Java that you download from Sun does not support JS in JEditorPanes, no.
    There is a library called Rhino which is a JS implementation for Java. I don't know if there's any way to get JEditorPane to use it. I would suspect not, but check out the Rhino site and they might have that info.

Maybe you are looking for

  • Left justify images in slideshow

    Is there a way to have the photos all line up on the left instead of centered in a slideshow?

  • [SOLVED]devmon - how to mount without "noexec" flag

    EDIT: Solution is in the last post. Hello, I'm using devmon and now I'd like to execute simple bash script on my harddisk. But unfortunately, devmon is mounting this disc as this: devmon: /usr/bin/udevil --mount /dev/sdb1 --mount-options "noexec,nosu

  • Does the HDMI cable carry both video and audio? U

    Does the HDMI cable carry both video and audio? If so what is the purpose of the separate optical audio connection? Just a little confusion setting the Apple TV Up with my AV receiver. TIA.

  • Advice appreciated

    Hello, I made the switch from PC to Mac over the summer. I keep wondeirng why I did not make the switch earlier. I have just purchased a G5 Powermac with Dual 2.0 and 2 Gigs of Ram. In addition I purchased Final Cut Studio. I have very little experie

  • Configuring WM in Already Implemented SAP ECC 6.0

    Dear all, In my SAP system all modules like MM,SD,FICO,PP are implemented. Now we want to implement SAP WM module in already implemented System, So what are the Key Points to consider While implementing the WM module. Regards, Rocky.