JEditorPane to JScrollPane

I have a perfectly good working JEditorPAne wich is transparent and it should be, now I want a scrollbar becouse the HTML-doc I reads into it is to large so I made a JScrollPane of my JEditorPane and then it stopped being transperent......how do I fix this?

scrollPane.getViewport().setOpaque(false);

Similar Messages

  • JEditorPane inside JScrollPane flickers somethin awful

    I'm working on an instant messenger/chat application, and I've noticed that when there is 'heavy' traffic, the JEditorPane flickers quite badly. The following code demonstrates the problem:
    import javax.swing.*;
    import java.awt.*;
    public class Test extends JFrame {
      public Test() {
        JEditorPane jep = new JEditorPane("text/html", "");
        StringBuffer sb = new StringBuffer();
        JScrollPane jsp = new JScrollPane(jep);
        this.setSize(640,480);
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(jsp, BorderLayout.CENTER);
        this.setVisible(true);
        for(int i = 0; i < 200; i++) {
          sb.insert(0, i+"<br>");
          jep.setText(sb.toString());
      public static void main(String[] args) { new Test(); }
    }I'm using JEditorPane because it's easy to change I can use html tags to alter the font color/size/properties/etc.... As well, users can embed links which will then open in a browser. Is there a better way of doing this? I've tried setDoubleBuffered(true/false) on various combinations of components, using String concatenations, and setting the StringBuffer's initial length to a largish number (~5000). Nothing seems to alter the results. This problem occurs on linux and NT4 with jdks 1.3.0_002, 1.3.1, 1.4. If someone can help I'd be really grateful. I want the target jdk to be 1.3.1, so anything that came in with 1.4 isn't really an option.
    Thanks in advance,
    m

    Kurt,
    Thanks, I think that did the trick. I still have to put it into the chat app, but it works great with the test app. One thing, I do want the new text to be inserted at the top, not appended, so I changed the read statement to:
    jep.getEditorKit().read(new java.io.StringReader(i+"<br>"), doc, 0);and that throws an exception:java.lang.RuntimeException: Must insert new content into body element-
         at javax.swing.text.html.HTMLDocument$HTMLReader.generateEndsSpecsForMidInsert(HTMLDocument.java:1716)
         at javax.swing.text.html.HTMLDocument$HTMLReader.<init>(HTMLDocument.java:1692)
         at javax.swing.text.html.HTMLDocument$HTMLReader.<init>(HTMLDocument.java:1564)
         at javax.swing.text.html.HTMLDocument$HTMLReader.<init>(HTMLDocument.java:1559)
         at javax.swing.text.html.HTMLDocument.getReader(HTMLDocument.java:118)
         at javax.swing.text.html.HTMLEditorKit.read(HTMLEditorKit.java:237)
         at Test.<init>(Test.java:25)
         at Test.main(Test.java:38)but if I change position to 1 it works fine. Any explanation? The source for EditorKit says:
         * @param pos The location in the document to place the
         *   content >= 0.m

  • JScrollPane wont scroll .. pls help

    hi to all,
    I have a scrollpane that i am displaying a graph in, and they will be large graphs, 10000 nodes with about cardinality 10 for each node.
    I can generate the graph output no problems but my scrollbars dont allow me to scroll the pane, and i cant figure out why.
    I'm assuming that i should be doing something with the viewport once i add the graph, but i dont know what.
    can anyone pls help me,
    also can anyone suggest how i go about zooming in and out. im thinking its just resizng the viewport, but i need to work out why i cant scroll before i tackle that.
    package graphappz.ui;
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import graphappz.graph.Graph;
    import java.util.Iterator;
    import graphappz.graph.Vertex;
    import graphappz.graph.Edge;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class GraphWindow
        extends JPanel {
      JEditorPane graphWindow;
      JScrollPane graphView;
      Dimension d = new Dimension();
      Point2D p = null;
      GraphViewer viewer;
      public GraphWindow() {
        graphWindow = new JEditorPane();
        graphWindow.setText("");
        viewer = new GraphViewer();
        graphView = new JScrollPane(viewer);
        graphView.setHorizontalScrollBarPolicy(JScrollPane.
                                               HORIZONTAL_SCROLLBAR_ALWAYS);
        graphView.setVerticalScrollBarPolicy(JScrollPane.
                                             VERTICAL_SCROLLBAR_ALWAYS);
        graphView.getViewport().setBackground(Color.white);
        graphView.setBorder(BorderFactory.createEtchedBorder());
        graphView.setToolTipText("Graph Output Display Window");
        repaint();
      public JScrollPane getGraphView() {
        return this.graphView;
      public Dimension getSize() {
        graphView.setPreferredSize(new Dimension(520, 440));
        return graphView.getPreferredSize();
      class GraphViewer
          extends JPanel {
        public void paintComponent(Graphics g) {
          super.paintComponent(g);
          int nodeWidth = 20;
          int nodeHeight = 20;
          if (graphappz.Main.graph != null) {
            Graph graph = graphappz.Main.graph;
            Iterator iter = graph.edgeIter();
            while (iter.hasNext()) {
              Edge e = (Edge) iter.next();
              Vertex v_0 = e.getv0();
              Vertex v_1 = e.getv1();
              if ( ( (v_0.getLayoutPosition() != null) ||
                    (v_1.getLayoutPosition() != null))) {
                Point2D.Double pos_0 = v_0.getLayoutPosition();
                Point2D.Double pos_1 = v_1.getLayoutPosition();
                // draw the edge
                g.setColor(Color.red);
                g.drawLine( (int) pos_0.x + (nodeWidth / 2),
                           (int) pos_0.y + (nodeHeight / 2),
                           (int) pos_1.x + (nodeWidth / 2),
                           (int) pos_1.y + (nodeHeight / 2));
                // draw the first node
                g.setColor(Color.blue);
                g.drawOval( (int) pos_0.x, (int) pos_0.y, nodeWidth, nodeHeight);
                g.fillOval( (int) pos_0.x, (int) pos_0.y, nodeWidth, nodeHeight);
                // draw the second node
                g.setColor(Color.blue);
                g.drawOval( (int) pos_1.x, (int) pos_1.y, nodeWidth, nodeHeight);
                g.fillOval( (int) pos_1.x, (int) pos_1.y, nodeWidth, nodeHeight);
                // draw the edge
                g.setColor(Color.black);
                g.drawString(v_0.getReference() + "", (int) pos_0.x + 5,
                             (int) pos_0.y + 14);
          else {
            graphappz.util.Debug.debugText.append("\n graph is null, can't draw it");
            //TODO: show new Alert_Dialog
        public GraphViewer() {
          this.setBackground(Color.white);
          this.addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent e) {}
            public void mousePressed(MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {}
            public void mouseEntered(MouseEvent e) {}
            public void mouseExited(MouseEvent e) {}
    }

    Scrollbars will appear when the preferred size of the panel is greater than the preferred size of the scrollpane.
    When you add components (JButton, JTextField...) to a panel then the preferred size can be calculated by the layout manager.
    When you draw on a panel the layout manager has no idea what the size of you panel is so you need to set the preferrred size yourself:
    panel.setPreferredSize(...);

  • Scrolling with images in a jeditorpane

    Hi,
    I'm really struggling with a jeditor pane. I'm using it to show formatted system messages in the interface i'm writing. In some cases these messages may include an image (usually a reference to an online image using html <img> tags.)
    What I want to do is automatically scroll to the bottom of the pane when new text is added. If i use only html formatted text this works fine, but as soon as there is an image in there it doesn't scroll far enough. I believe what's happening is that the image has not finished loading so it scrolls only the length of the placeholder.
    This is the code i'm using to scroll:
    JEditorPane IMPane;
    JScrollPane IMScroller;
    //...snip...
    private void scrollPaneToBottom(){
            SwingUtilities.invokeLater(new Runnable(){
                public void run(){
                    if (isAdjusting()){
                        return;
                    int height = IMPane.getHeight();
                    IMPane.scrollRectToVisible(new Rectangle(0, height - 1,1, height));
        private boolean isAdjusting(){
            JScrollBar scrollBar = IMScroller.getVerticalScrollBar();
            if (scrollBar != null && scrollBar.getValueIsAdjusting()){
                return true;
            return false;
        }I have tried various options including moving the caret but to no avail. Perhaps there is some way i can wait till the page is fully loaded or something like that?
    I hope somebody can help me with this - it's driving me bananas.
    Thanks in advance,
    Crystal

    In the future, Swing related questions should be posted in the Swing forum.
    I would guess your isAdjusting() method is returning true, so the code never executes.
    An easier way to scroll to the bottom is to use:
    textComponent.setCaretPosition( textComponent.getDocument().getLength() );

  • Smearing of JInternalFrame inside JScrollPane

    Hi All,
    Ran into a very interesting problem that I thought someone may have seen. When using JInternalFrame in a JScrollPane I discovered an interesting painting problem. If the scrollbars are visible and I slowly move a JInternalFrame so it's visible area goes past the where the scrollbar is painted then slowly slide back the JInternalFrame so it's frame is uncovered I get a smearing of the JScrollPane on the JInternalFrame. If I resize the JInternalFrame the frame is redrawn correctly.
    Any ideas how to fix this? I am using jre 1.4.2_03
    Thanks.

    Here's some code to explain the problem....
    import javax.swing.*;
    import java.awt.*;
    import java.io.IOException;
    public class ScrollTest extends JFrame {
         JPanel wholePanel;
         JPanel imagePanel;
         JPanel htmlPanel;
         JEditorPane editPane;
         JScrollPane scrollPane;
         public ScrollTest() {
              super("JScrollPaneTest");
              imagePanel = new JPanel();
              imagePanel.setBackground(Color.red);
              imagePanel.add(new JLabel("image here"));
              editPane = new JEditorPane();
              editPane.setEditable(false);
              try {
                   editPane.setPage("http://www.isness.org/adam/netzspannung/help.html");
              } catch (IOException ioe) {
                   System.err.println("Couldn't get page");
              wholePanel = new JPanel();
              wholePanel.setLayout(new BoxLayout(wholePanel, BoxLayout.Y_AXIS));
              wholePanel.add(imagePanel);
              wholePanel.add(editPane);
              // first one works fine (ie. has vertical scrollbar), second sizes incorrectly (ie. has horizontal scrollbar)
              //scrollPane = new JScrollPane(editPane);
              scrollPane = new JScrollPane(wholePanel);
              getContentPane().add(scrollPane);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setBounds(0, 0, 300, 300);
         public static void main(String[] args) {
              ScrollTest st = new ScrollTest();
              st.setVisible(true);
    }

  • Maybe I havent found it yet but...

    Is there a way to set a buffer size to a JEditorPane? It will be placed inside a JScrollPane so maybe it needs to be done via the scroll pane...
    The plan is to have a mudclient type interface (it isnt for a mud client just using it as an example) where after the data is processed it is displayed at the bottom of the EditorPane, after so many lines eventually the text at the top of the editor pane is scrolled off the top, so if the user wants they can scroll back and look at previous information...
    I am still in brain storming phase so any suggestions would be appreciated.

    Didn't see a set JEditorPane method for it, but this does:
    public class TextAreaTest {
         JEditorPane jep;
         JScrollPane jsp;
         JFrame jf;
         JPanel north;
         JPanel west;
         JPanel south;
         JPanel east;
         JPanel content;
         JTextField jtf;
         JButton jb;
         int count = 1;
         int BUFFERSIZE = 100;
         String[] buffer = new String[BUFFERSIZE];
         int numEntries = 0;
         public TextAreaTest() {
              jep = new JEditorPane();
                   jep.setEditable(false);
                   jep.setFocusable(false);
                   jep.setPreferredSize(new Dimension(300,200));
              jsp = new JScrollPane(jep);
                   jsp.setPreferredSize(new Dimension(300,200));
              north = new JPanel();
                   north.setPreferredSize(new Dimension(400,50));
              west = new JPanel();
                   west.setPreferredSize(new Dimension(50, 300));
              east = new JPanel();
                   east.setPreferredSize(new Dimension(75, 300));
              jtf = new JTextField("Add Some Text Here");
                   jtf.setPreferredSize(new Dimension(300,50));
              jb = new JButton ("Add");
                   jb.setPreferredSize(new Dimension(75,50));
                   jb.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             //Gives values 0 to BUFFERSIZE
                             int newEntry = numEntries++ % BUFFERSIZE;
                             buffer[newEntry] = "This is entry #" + numEntries;
                             StringBuffer sb = new StringBuffer();
                             //This will be the index of the buffer that is being added to
                             //the StringBuffer
                             int place = 0;
                             //If there are more than BUFFERSIZE entries, then we
                             //should start adding not from zero, but from the
                             //newset entry onward
                             if (numEntries > BUFFERSIZE) {
                                  place = newEntry + 1;
                             //This is the total number of entries to add.  If total entries
                             //made are less than BUFFERSIZE, only cycle numEntries times,
                             //otherwise cycle BUFFERSIZE times.
                             int lastEntry = (numEntries < BUFFERSIZE) ? numEntries : BUFFERSIZE;
                             for (int i = 0; i < lastEntry; i++){
                                  //When place reaches BUFFERSIZE, start from the beginning
                                  //of the buffer
                                  if (place == BUFFERSIZE)
                                       place = 0;
                                  sb.append(buffer[place++] + '\n');
                             jep.setText(sb.toString());
              south = new JPanel();
                   south.setLayout(new BoxLayout(south, BoxLayout.X_AXIS));
                   south.add(Box.createHorizontalStrut(50));
                   south.add(jtf);
                   south.add(jb);
                   south.setPreferredSize(new Dimension(425, 50));
              content = new JPanel();
                   content.setLayout(new BorderLayout());
                   content.add(north, BorderLayout.NORTH);
                   content.add(west, BorderLayout.WEST);
                   content.add(jsp, BorderLayout.CENTER);
                   content.add(east, BorderLayout.EAST);
                   content.add(south, BorderLayout.SOUTH);
              jf = new JFrame ("Look at My JEditor Frame");
                   jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                   jf.setContentPane(content);
                   jf.pack();
                   jf.setVisible(true);
         public static void main(String[] args) {
              TextAreaTest tat = new TextAreaTest();
    }

  • JTable: scrollabel Cell

    Hi,
    I've already come up with this, but up to now I haven't received any answer.
    What do I have to do, to can I scroll a non editable cell within a JTable?
    Besides the CellRenderer, I have to implement the CellEditor. But I something is wrong, it just won't work.
    code snippet from celleditor:
    public class ScrollPaneCellEditor extends JScrollPane implements TableCellEditor, Serializable{
    JEditorPane pane;
    JScrollPane scrollpane;
    StringBuffer sb;
    /** Creates a new instance of IconTableCellRenderer */
    public ScrollPaneCellEditor() {      
    pane = new JEditorPane();
    sb = new StringBuffer(); }
    public boolean isCellEditable(java.util.EventObject anEvent) {
    return false;
    public java.awt.Component getTableCellEditorComponent(javax.swing.JTable table, Object value, boolean isSelected, int row, int column) {
    pane.setText(value.toString());
    super.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JViewport vp = new JViewport();
    vp.setScrollMode(JViewport.BLIT_SCROLL_MODE);
    vp.setView(pane);
    super.setWheelScrollingEnabled(true);
    if (isSelected){           
    scrollpane.setViewport(vp);
    if(hasFocus()){
    scrollpane.setViewportView(vp);
    super.add(vp);
    return this;
    Best regards,
    Andi

    Hi bukibu79 ,
    In JTable cells are not a component
    it is a painting using graphics, when you edit a cell this time the editable cell only a component so you cann't edit two cells at a time.
    Another one is suppose you assume that cell are compoents then how can add a single component into two different cells. What actualy do on JTable is , JTable get the component form the renderer and paint this renderer component into the cell's rectangle area and move this component to some non visible area.
    If your table cell is non editable then the editor doesn't work because there are no need to get editor for JTable.

  • Graphical editor

    Hi,
    I'm trying to make a graphical DTD editor. Right now I have a little problem with moveable objects and arrows. Perhaps someone can help me with this?
    I'll try to describe my problem as good as I can. First, there should be some objects like squares or circles (moveable one). Second, every object have a different meaning (like square is some kind a node or value). So we have couple of squares and circles, we're connecting them with our arrows and we suppose to have a nice DTD document. Yes, I know ... Right now I need some information how to put one object on it place (when we click on the square it stops to move and we can play with another one). Please forgive me my English but I'm not an native speaker.
    Cheers.
    ----some of my code---
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.BevelBorder;
    import javax.swing.event.MouseInputAdapter;
    import javax.swing.text.Highlighter;
    import java.io.*;
    public class DTDEdit extends JFrame
         OptionsTB     _op;
         FunctionsTB     _fu;     
         JTabbedPane _ta;
         * This is main constructor.
         * In here we're cooking all fancy stuff.
         * @param _ch is a JFileChooser. Thank to this he can open
         * a file.
         public DTDEdit() {
              _ta = new JTabbedPane();
              _op = new OptionsTB();
              _fu = new FunctionsTB();
              ImageIcon ic = new ImageIcon("images/icons/Earth-16x16.png");
              JPanel panel = new JPanel();
              //JPanel panel2 = new JPanel();          
              //TODO To nadal jest puste.
              SecondPanel panel2 = new SecondPanel();
              panel2.setVisible(true);
              panel.setBorder(new BevelBorder(BevelBorder.LOWERED));
    OverlayLayout overlay = new OverlayLayout(panel);
    panel.setLayout(overlay);
    panel.add(new TopPanel("123"));
    panel.add(new Overlay());
    _ta.addTab("graphical",ic, panel);
    _ta.addTab("source",ic, panel2);   
    add(_ta, "Center");
              setJMenuBar(new Menu());
              getContentPane().add(_op, BorderLayout.NORTH);
              getContentPane().add(_fu, BorderLayout.WEST);
              pack();
         public int scWidth() //get width of screen number 1
              GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
         GraphicsDevice[] gs = ge.getScreenDevices();
         DisplayMode dm = gs[0].getDisplayMode();
         return dm.getWidth();
         public int scHeight() //get height of screen number 1
              GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
         GraphicsDevice[] gs = ge.getScreenDevices();
         DisplayMode dm = gs[0].getDisplayMode();
         return dm.getHeight();
         public static void main(String[] args) {
    DTDEdit f = new DTDEdit();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(800,600);
    f.setLocation(200, 200);
    f.setVisible(true);
    * This determines an movable editor
    * @author Marcin
    class Overlay extends JPanel
    public Overlay()
    setBackground(Color.LIGHT_GRAY);
    * This is top panel.
    * We're painting on it.
    * @author Marcin
    class TopPanel extends JPanel
    Point loc;
    int width, height, arcRadius;
    Rectangle r;
    String s;
    public TopPanel(String s)
         this.s = s;
    setOpaque(false);
    width = 80;
    height = 40;
    arcRadius = 0;
    r = new Rectangle(width, height);
    TopRanger ranger = new TopRanger(this);
    addMouseListener(ranger);
    addMouseMotionListener(ranger);
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
    RenderingHints.VALUE_ANTIALIAS_ON);
    if(loc == null)
    init();
    g2.setPaint(Color.DARK_GRAY);
    g2.fillRoundRect(loc.x, loc.y, width, height, arcRadius, arcRadius);
    g2.setPaint(Color.yellow);
    g2.drawString(s, loc.x + 25, loc.y + 25);
    //g2.drawRoundRect(loc.x, loc.y, width, height, arcRadius, arcRadius);
    private void init()
    int w = getWidth();
    int h = getHeight();
    loc = new Point();
    loc.x = (w - width)/2;
    loc.y = (h - height)/2;
    r.x = loc.x;
    r.y = loc.y;
    public int getRectWidth()
         return width;
    * In here we're enabling an mouse adapters.
    * Thank's to this we can move what we had made :)
    * @author Marcin
    class TopRanger extends MouseInputAdapter
    TopPanel top;
    Point offset;
    boolean dragging;
    public TopRanger(TopPanel top)
    this.top = top;
    offset = new Point();
    dragging = false;
    public void mousePressed(MouseEvent e)
    Point p = e.getPoint();
    if(top.r.contains(p))
    offset.x = p.x - top.r.x;
    offset.y = p.y - top.r.y;
    dragging = true;
    public void mouseReleased(MouseEvent e)
    dragging = false;
    // update top.r
    top.r.x = top.loc.x;
    top.r.y = top.loc.y;
    public void mouseDragged(MouseEvent e)
    if(dragging)
    top.loc.x = e.getX() - offset.x;
    top.loc.y = e.getY() - offset.y;
    top.r.setSize(65, 25);
    top.repaint();
    * Menus and other things.
    * I've made this for two reasons
    * 1) Every application has things like this.
    * 2) It's a pretty cool when you don't have to
    *      search for something in embedded option of
    *      application.
    * @author Marcin
    //     Our little menu
    class Menu extends JMenuBar                         //Still not finished
         JMenu File = new JMenu("File");
         JMenu Edit = new JMenu("Edit");
         JMenuItem firstItem = new JMenuItem("first");
         JMenuItem secondItem = new JMenuItem("second");
         Menu(){
              File.add(firstItem);
              add(File);
              Edit.add(secondItem);
              add(Edit);
    class OptionsTB extends JToolBar implements ActionListener                    //Still not finished
         ImageIcon sa = new ImageIcon("images/icons/Save24.gif");
         ImageIcon op = new ImageIcon("images/icons/Open24.gif");
         JButton _open;
         JButton _save;
         Separator sep1;
         JFileChooser _ch;
         OptionsTB()
              _open  = new JButton("Open", op);
              sep1 = new Separator();
              _save  = new JButton("save", sa);
              _open.addActionListener(this);
              _save.addActionListener(this);
              _ch = new JFileChooser();
              add(_open);
              add(_save);
              add(sep1);
              setFloatable(false);
              setSize(100, 50);
    // TODO Open and save handler
         public void actionPerformed(ActionEvent e)
              if( e.getSource() == _open){
                   int returnVal = _ch.showOpenDialog(OptionsTB.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = _ch.getSelectedFile();
         //TODO We should have a file handler in here.
    } else
    if (e.getSource() == _save) {
         int returnVal = _ch.showSaveDialog(OptionsTB.this);
    if (returnVal == JFileChooser.APPROVE_OPTION);
         File file = _ch.getSelectedFile();
              //TODO We should have a save handler in here.
    class FunctionsTB extends JToolBar                    //Still not finished
         JButton _check;      
         ImageIcon star = new ImageIcon("images/icon/Star.png");
         FunctionsTB()
              _check = new JButton("Check", star);
              add(_check);
              setFloatable(false);
              setOrientation(VERTICAL);
              setSize(100, 50);
    class SecondPanel extends JPanel
         JEditorPane pane;
         JScrollPane scroll;
         public SecondPanel() {
              pane = new JTextPane();
              //pane.setBackground(Color.BLACK);
              pane.setText("Pierwsza linia");
              pane.setBackground(Color.BLACK);
              pane.setForeground(Color.WHITE);
              pane.setEditable(false);
              scroll = new JScrollPane(pane);
              scroll.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              scroll.setPreferredSize(new Dimension(600, 600));
              scroll.setMinimumSize(new Dimension(800, 600));
              add(scroll);
              JScrollPane scroll = new JScrollPane();
    --- THE END OF MY STUFF ---

    Hi nordvik_
    I developed a component that does exactly what you are talking about. Would you be interested in buying a copy?
    This is not a simple project, but if you're determined to build it yourself, here's a few hints
    1. How are you going to represent your nodes? Will they be components? The advantage of this is that with Components its easy to set size, implement painting. The disadvantage is that it's difficult to draw lines between components, and they will likely absorb mouse events that are outside of the shape's area (unless all your shapes are rectangles)
    2. How are you going to move + resize the components? If you search google for draggable.java/resizeable.java tjacobs01 you'll find some classes that I've previously posted that drag / resize components. This may or may not be helpful
    3. How are you going to internally represent the connection lines? how are you going to draw them? How are you going to figure out start and end points?
    If you're potentially interested in buying a copy of my source code, plz post your email address and I will contact you
    Edited by: tjacobs01 on Aug 10, 2008 2:17 PM

  • A JTextPane question (5 Duke Dollars)

    Hi, I'm doing a large project in java and have ran into several issues. Most have already been answered, but this one keeps nagging on:
    1. How would I make certain words certain colours/formats? I have set up a text box like this:
    static JTextPane luacode = new JTextPane();
    then in the code this happens:
         sbrText = new JScrollPane(textbox);
         textbox.addKeyListener(new MyKeyListener());
         //scrollpane
         sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
         //scrollbar
         sbrText.setPreferredSize(new Dimension(685, 370));
    but does anyone have any idea about formatting this, e.g. if apple is said make it green and bold, if the letters // are typed then anything else on that line is green and font system etc...
    Thank you
    Alex
    null

    You might want to consider this strategy.
    Use a JTextEditor.
    Set the editor kit to be HTMLEditorKit.
    now you can use html to alter the apearance / formating of your document.
    want to make apple bold. just add <b> apple </b>
    The screen will update in real time.
    The user never needs to know they are working in html. this can just be the background implementation.
    if you need source to reference just let me know.. i might be able to provide you with a quick example.
    Message was edited by:
    jmguillemette
    example code..
    package com.wirednorth.examples.editor;
    import java.awt.Dimension;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.text.html.HTMLEditorKit;
    public class MyEditor extends JFrame{
         private JEditorPane editorPnl = new JEditorPane();
         private JScrollPane scrollPnl = new JScrollPane(editorPnl);
         public MyEditor(){
              setSize(800,600);
              setTitle("Editor example");
              editorPnl.setEditorKit(new HTMLEditorKit());
              editorPnl.setPreferredSize(new Dimension(400,400));
              getContentPane().add(scrollPnl);
              editorPnl.setText(
                                       "<html>" +
                                            " my apple is <font color='green'>Green</font>" +
                                       "</html>"
         public static void main(String[] args) {
              MyEditor editor = new MyEditor();
              editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              editor.setVisible(true);
    }

  • HTML TextArea is a  JScrollPane in JEditorPane?

    Hi all,
    I'm trying to create an autofill facility for my application, to do this I am getting the components from the HTML document and converting them to their Java Swing counterpart.
    So for example <input type="text" name="example" /> would be a normal text input field on a HTML form, and its Swing conversion is a JTextField - this works as desired and it allows me to use the .settext() command to set the text on the HTML form - i.e. autofilling.
    My problem comes when I try to get the component for a HTML textarea, e.g. <textarea name="example"></textarea> - I would expect the Swing component to be a JTextArea, but the class it gets converted to is a JSrcollPane! This leads to a problem as I can't set the text of a JScrollPane as it is a container.
    Does anyone know how I might get around this problem so that I can set the text for the textarea? I've included my code below.
    Many thanks
    BBB
    import java.awt.event.*;
    import java.awt.*;
    import java.net.URL;
    import javax.swing.*;
    public class Tester extends JFrame{
        static JEditorPane pane = new JEditorPane();
        public Tester()
            try {
                pane.setPage( new URL("http://www.amray.com/cgi/amray/addurl.cgi") );
            } catch (Exception e) {
            this.getContentPane().add(new JScrollPane(pane));
            JButton b1 = new JButton("Auto Fill");
            this.getContentPane().add(b1,BorderLayout.SOUTH);
            b1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e)
                    for ( int i = 0; i < pane.getComponentCount(); i++ )
                        Container c = (Container)pane.getComponent(i);
                        Component swingComponentOfHTMLInputType = c.getComponent(0);
                        System.out.println(swingComponentOfHTMLInputType.getClass());
                        if ( swingComponentOfHTMLInputType instanceof JTextField ) {
                            JTextField tf = (JTextField)swingComponentOfHTMLInputType;
                            tf.setBackground( Color.yellow );
                            tf.setText("Auto Filled");
                        if ( swingComponentOfHTMLInputType instanceof JScrollPane ) {
                            JScrollPane ta = (JScrollPane)swingComponentOfHTMLInputType;
        public static void main(String args[]) {
            Tester app = new Tester();
            app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            app.setSize( 400, 400 );
            app.setVisible( true );
    }

    Hi Jim,
    Thanks for the suggestion, but I've already tried that and although it does work from a visual POV, when you then submit the form the data in the JTextArea isn't added - it just says the field is blank.
    Although, I'm not sure whether it's not working due to the method I've had to use to add the JTextArea: -
    JScrollPane ta = (JScrollPane)swingComponentOfHTMLInputType;
    JTextArea oTextArea = new JTextArea();
    oTextArea.setText("Hello World!");
    ta.setViewportView(oTextArea);I'm not sure if it's not working because I've had to use .setViewportView(); rather than .add(). If I use .add() then no changes are reflected on screen and the JTextArea isn't actually added.
    Any other suggestions?

  • JEditorPane not scrolling in JScrollPane no matter what

    Hello,
    I thoroughly researched this problem and I tried all suggestions, but nothing seems to work. I have a JEditorPane inside the JScrollPane, but JEditorPane does not scroll horizontally no matter what. It simply cuts off the text to the right.
    Here is my code:
    reportArea = new JEditorPane() {
    public boolean getScrollableTracksViewportWidth() {                   
    if (getSize().width < getParent().getSize().width)
         return true;
    else
         return false;
    public void setSize(Dimension d) {                   
    if (d.width < getParent().getSize().width)
         d.width = getParent().getSize().width;
    super.setSize(d);
    reportArea.setEditorKit(new HTMLEditorKit());
    reportArea.setEditable(false);
    JScrollPane reportJ = new JScrollPane(reportArea);
    reportJ.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    reportJ.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    Any suggestions will be greatly and truly appreciated!
    Elana

    I need to display HTML page, that's why I need JEditorPane. Also, In the html table that I'm displaying I have the nowrap attribute, so nothing gets wrapped at all. It's just being cut off...
    ;-(

  • Determining the visible lines of a JEditorPane within a JScrollPane

    I need to track what lines are visible (the Document line numbers) within the Viewport of a JScrollPane that contains a JEditorPane. Is this achievable?

    That's a tricky one.
    Maybe something like this:
    First get the view coordinate of the top left corner of the view port
    Point p = scrollPane.getViewPort().getViewPosition();Then convert that view location into a model location. The model location will be an index into the document.
    int modelLocation = editorPane.viewToModel( p );Now you just need to count how many lines are before this index location. As I recall there is a main root element for the whole document. The root element is made up of child elements, one for each line. This may be different for HTML but might work for text or rich text.
    Element rootElement = editorPane.getDocument().getRootElements()[0];
    // getElementIndex() will give you the child element index (e.g. line element that is at the given document location).
    int lines = rootElement.getElementIndex( modelLocation );Do the same for the point location that is at the viewport's location plus the viewport's size (i.e. the lower right corner of the viewport).
    There is a LOT of speculation here since I haven't actually put this to a test case. But maybe its enough to point you in a direction that works.
    -Mike

  • JEditorPane + JScrollPane

    hi,
    This is the code :
    JEditorPane edit = new JEditorPane("text/html",ajout);
    JScrollPane scroll = new JScrollPane(edit,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    editScroll.add(edit);
    why this code doesn't work ?

    This thread works for a JTextPane, not sure about JEditorPane:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=326017

  • 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();
    }

  • How can I create JEditorPane which scrolls to the bottom on every resize?

    JRE 1.3.0
    Included a simple frame with the only control - JEditorPane (contained within JScrollPane). Every time scroll pane size changes, attempt to scroll down to the end of JEditorPane is made.
    The problem is: although everything works 9 times of 10, sometimes editor is scrolled almost to the end, sometimes - to the very top. On the next resize editor is scrolled correctly.
    I think, there are some delayed layout recalculations inside SWING which prevent JEditorPane and/or JScrollPane from knowing actual size.
    Is it possible to force JEditorPane+JScrollPane pair to update dimensions? ( explicit call to doLayout() does not fix anything )
    Thanks
    public class TestFrame extends JFrame
    BorderLayout borderLayout1 = new BorderLayout();
    JScrollPane jScrollPane1 = new JScrollPane();
    JEditorPane jEditorPane1 = new JEditorPane();
    public TestFrame()
    try
    jbInit();
    catch(Exception e)
    e.printStackTrace();
    private void jbInit() throws Exception
    this.getContentPane().setLayout(borderLayout1);
    jEditorPane1.setContentType("text/html");
    jEditorPane1.setText("test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test ");
    jScrollPane1.addComponentListener(new java.awt.event.ComponentAdapter()
    public void componentResized(ComponentEvent e)
    jScrollPane1_componentResized(e);
    this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
    jScrollPane1.getViewport().add(jEditorPane1, null);
    void jScrollPane1_componentResized(ComponentEvent e)
    Dimension size = jEditorPane1.getPreferredSize();
    jEditorPane1.scrollRectToVisible( new Rectangle(0, size.height, 0, 0) );
    System.out.println("preferred height=" + size.height);
    }

    Seen this thread?
    Return to previously viewed page

Maybe you are looking for