Adding a JScrollPane to a JTextPane

Hi,
I'm having problems adding a JScrollPane to a JTextpane. I expected you could add it just as you do with a JTextPane but for some reason it does not appear. Here is the code:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
class ChatRoom extends JFrame implements ActionListener
     private     DefaultStyledDocument     doc;
     private     JTextPane                    pane;
     private JButton blueb, yellowb, redb, cyanb;
     private StyleContext sc;
     private JScrollPane scroll;
     public ChatRoom()
          setTitle( "Document     Handling Application" );
          setSize( 300, 190 );
          setBackground( Color.gray );
          JPanel topPanel     = new JPanel( new BorderLayout() );
          getContentPane().add( topPanel );
          // Create styles for the document
          sc = new StyleContext();
          doc = new DefaultStyledDocument( sc );
          // Create a text pane to display text
          pane = new JTextPane( doc );
          pane.setBackground( Color.white );
          pane.setEditable(false);
          scroll = new JScrollPane(pane);
          scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
          scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
          topPanel.add( pane, BorderLayout.CENTER );
          blueb = new JButton("Blue");
          blueb.setBackground(Color.blue);
          blueb.addActionListener(this);
          yellowb = new JButton("Yellow");
          yellowb.setBackground(Color.yellow);
          yellowb.addActionListener(this);
          redb = new JButton("Red");
          redb.setBackground(Color.red);
          redb.addActionListener(this);
          cyanb = new JButton("Cyan");
          cyanb.setBackground(Color.cyan);
          cyanb.addActionListener(this);
          JPanel buttonPanel = new JPanel();
          buttonPanel.add(blueb);
          buttonPanel.add(yellowb);
          buttonPanel.add(redb);
          buttonPanel.add(cyanb);
          topPanel.add(buttonPanel, BorderLayout.SOUTH );
     // Handle changes to the combobox (style changes)
     public void actionPerformed( ActionEvent e )
          MutableAttributeSet attr = new SimpleAttributeSet();
          if(e.getSource() == blueb) {
               StyleConstants.setForeground(attr, Color.blue);
          if(e.getSource() == yellowb) {
               StyleConstants.setForeground(attr, Color.yellow);
          if(e.getSource() == redb) {
               StyleConstants.setForeground(attr, Color.red);
          if(e.getSource() == cyanb) {
               StyleConstants.setForeground(attr, Color.cyan);
          pane.setCharacterAttributes(attr, false);
          try { doc.insertString( pane.getCaret().getDot(), "Hello \n", attr ); }
          catch( BadLocationException exception ) {}
          pane.grabFocus();
     // Main() method to     get     the ball rolling
     public static void main( String args[] )
          // Create an instance of the test application
          ChatRoom mainFrame     = new ChatRoom();
          mainFrame.setVisible( true );
}Thanks
Cath

yeah sorry, i'm being realy dumb :-), thanks very much for your help!
Cath

Similar Messages

  • Losing JToolTips when adding to JScrollPane

    I'm using a large ImageIcon as a JLabel in a JFrame, with other small JLabels over top of it. I've added tool tips to the smaller jlabels, and everything looks ok, and I get the jtooltips to fire normally. The problem is that the image is too large for the screen, so I need to be able to scroll it.
    public class GelFrame extends JFrame {
        public GelFrame(.......) {
          // add main gel image
          JLabel GEL = new JLabel(new ImageIcon(image));
          GEL.setBounds(0,0,width,height);
          getContentPane().add(GEL);
          // add the smaller JLabels here
          ArrayList spot = new ArrayList();
          for(int i=0; i<passedArrayList.size(); i++) {
            spot = (ArrayList)passedArrayList.get(i);
            System.out.println("protein: "+(String)spot.get(0));
            int x = ((Integer)spot.get(1)).intValue();
            int y = ((Integer)spot.get(2)).intValue();
            JLabel label = new JLabel();
            label.setBackground(new Color(000,255,000));
            // set the bounds of the new label
            label.setBounds(x+1, y+1, 3,3);
            System.out.println("** creating label with bounds: "+x+", "+y+", 3, 3");
            // add the tool tip text to the jlabel
            label.setToolTipText((String)spot.get(0));
            // add to the JFrame
            getContentPane().add(label);
    }When I add this JFrame to a JScrollPane, I get the proper scrolling, but I lose the jtooltips.

    koleber -
    Thanks for the reply!
    I made the suggested changes, and I'm still not able to see the jtooltips. Is there something about the viewport that gets in the way, or covers up the JPanel? Should it matter when I add the tooltip'd jlabels to the JPanel?

  • Adding a link to a JTextPane

    Hello to all,
    I use a JTextPane to edit HTML text. Now I want to enter a link into it. I thought about entering the URL and the pressing a button to make a link out of it.
    Another way would be to add a button. After the button will be pressed I open a dialog to enter the URL and it will be pasted into the document as link.
    Which way would be easier to implement? How do I make a link out of the selected text in a JTextPane? Or how do I paste a link at the selected position?
    Thank you in advance!

    I would start by doing a search of the forums
    http://search.java.sun.com/search/java/index.jsp?and=hyperlink+jtextpane&phr=&qt=&not=&field=&since=&nh=10&col=javaforums&rf=0&Search.x=45&Search.y=10

  • Help with adding an icon in a JTextPane

    Hy guys,
    i have the following code:
    Document doc = DisplayArea.getDocument();
    String temp = s.substring(0, s.indexOf("Smile"));
             doc.insertString(doc.getLength(), temp , st);
             Style regular = chatArea.addStyle("regular", def);
             Style stl = chatArea.addStyle("icon", regular);
             StyleConstants.setIcon(stl, new ImageIcon("smile.gif"));
             doc.insertString(doc.getLength(), s , stl);
             temp = s.substring(s.indexOf("Smile")+1+"Smile".length(), s.length()) + "\n";
             doc.insertString(doc.getLength(), temp , st);The problme is that after it displays the image the second part of the text on the next line.
    Is there any way to make it be all in one line with the image in the middle ?
    Thx in advance

    Sorry for this guys but i managed to solve it by looking in the forum
    thx anyway for wanting to help

  • Obnoxious JTextPane and JScrollPane problem.

    I have written a Tailing program. All works great except for one really annoying issue with my JScollPane. I will do my best to explain the problem:
    The program will continue tailing a file and adding the text to the JTextPane. When a user scrolls up on the JScrollPane, the program still adds the text to the bottom of the JTextPane and the user can continue to view what they need.
    Here is the problem: I have text being colored throughout the text pane. For instance, the word ERROR will be in red. The problem is when the program colors the text, it moves the scroll pane to the line where word that was colored is at. I don't want that. If the user moves the scroll bar, I want the scroll bar to always stay there. I don't want the program to move to the text that was just colored.
    Is there a way to turn that off? I can't find anything like that anywhere.

    Coloring text will not cause the scrollpane to scroll.
    You must be playing with the caret position or something.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JScrollPane (containing an expanding JTextPane)

    I am writing a chatroom program using Swing, so I have this JScrollPane wrapping a JTextPane where all the messages (conversations) are displayed. When a new message comes up, the program inserts it at the end of the JTextPane's StyledDocument. This is when some strange things happen (regardless of where is the JScrollPane's view). In the beginning, it scrolls to the very bottom automatically whenever a new message is inserted. However, sometimes, after I do some random manual scrolling, it just stays at the same location regardless if there is a new message inserted. This is obviously not what I would want for my chatroom.
    Instead, I want these behaviours when a new message is added:
    1) The JScrollPane will scroll to the bottom if it was already at the bottom before the message was added.
    2) The JScrollPane's view will stay at the same location if the user was viewing something in the middle of the JTextPane (not at the bottom).
    Please tell me how I can do this. Thanks!

    Thanks for the link which has very nice info on auto-scrolling.
    However, that only solved half of my problems.
    I don't want it to scroll when the user is viewing somewhere not at the bottom of the JScrollPane, which was the case (2) that I was describing. Can you suggest how I can do that?

  • Trouble Scrolling down(JTextPane inside JScrollPane)

    I am writting a java interface to the Jabber IM system. I'm trying to allow html in the messages, so I have a JTextPane that I use to show what has been said. In order to scroll, I've placed the JTextPane within a JScrollPane. When a new message needs to be placed into the JTextPane, I set the JTextPane to the proper text and set the scroll bar from the scroll pane to it's .getMaximum() value. My problem is that the .getMaximum() function only gets the NEW, ACTUAL maximum AFTER the JTextPane has been parsed and painted into the JPanel. The time it takes to do this is proportional to the length of the text within the JText pane and relative to the speed of the computer. So, the scroll bars should be done in response to the completion of the painting of the JTextPane instead of a set time delay. I don't know how to do this. I assume I need to overwrite some paint or repaint function, but I don't know which one to overwrite. The JTextPane is in a JScrollPane in a JSplitPane in a JPanel in a JFrame, if that helps at all.
    I've been stuck on this forever..
    Thanks for any help.

    Gave you 6 $. JTextPane doesn't have the insert function, so I've been using setText(). The problem is that the second the Pane is redrawn, it shows the top of the document, then scrolls to the bottom. This takes a fraction of a second, but still is undesireable.
    What I'm trying to do is make a new textpane object, set the text, set the caret position, THEN replace the old pane. The problem is, I can't just use oldPane = newPane because that just makes oldPane reference the new Object.(The object shown is then only referenced from the parent swing component, a JScrollPane) I've tried using the .setViewportView on the JScrollPane that the JTextPane is within, but then it doesn't scroll to the caret position.
    I've gotten it to work once. I had created all new objects(JTextPane within JScrollPane within JSplitPane within JPanel) adding each to it's parent and adding the JPanel to the container. This worked ONCE! I changed the code, then changed it back and it didn't work again...
    Here's the code I have for buffering the JTextPane.
    if(chatPane == chatPaneBuffer2){
    chatPaneBuffer1.setText(chatStringBuffer.toString());
    chatPaneBuffer1.setCaretPosition(chatPaneBuffer1.getDocument().getLength());
    chatPane = chatPaneBuffer1;
    }else{
    chatPaneBuffer2.setText(chatStringBuffer.toString());
    chatPaneBuffer2.setCaretPosition(chatPaneBuffer2.getDocument().getLength());
    chatPane = chatPaneBuffer2;
    This works, but somehow I need the object chatPane is pointing at to be referenced by my JScrollPane.

  • JTextPane inside JScrollPane resizing when updated

    Hiya all,
    I've been struggling with this problem and checking the forums, but didn't find a solution, so I hope someone can help...at least help me for the nice picture :) It has to do with JTextPane's automatically resizing to their content on a GUI update, rather than scrollbars appearing (the desired result).
    Basically, I have a scenario where I am creating a series of multiple choice answers for a question. Each answer consists of a JTextPane inside a JScrollPane, and a JRadioButton, which are all contained in a JPanel (called singleAnswerPanel). So for 2 answers, I would have 2 of these singleAnswerPanels. There is a one large JPanel that contains all the singleAnswerPanels (called allAnswersPanel). This allAnswersPanel is contained in a JScrollPane. Graphically, this looks like:
       |       JPanel (allAnswersPanel) inside a JScrollPane            |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
        ----------------------------------------------------------------So above, I show 2 answers that can be filled in with text. So assuming both answer JTextPanes are filled with text beyond their current border (scrollbars appear as expected) and the user wishes to add more answers. I have a button to add another singleAnswerPanel to the containing JPanel (allAnswersPanel), and then I validate the main JScrollPane that contains the allAnswersPanel as it's view. The problem that occurs is the existing single answer JTextPanes resize to the size of their text and the vertical scrollbars (only vertical ones setup) of the JTextPanes dissappear! My intent is to keep the existing JScrollPanes the same size (with their scrollbars) when a new answer is added.
    The code snippet below shows what gets done when a new answer is added:
    private void createAnswer()
        // The panel that will hold the new single answer JTextPane pane
        // (inside a JScrollPane) and radio button.
        JPanel singleAnswerPanel = new JPanel();
        // Create the text pane for the single answer.
        JTextPane singleAnswerTextPane = new JTextPane();
        Dimension dimensions = new Dimension(200, 30);
        singleAnswerTextPane.setPreferredSize(dimensions);
        singleAnswerTextPane.setMaximumSize(dimensions);
        // Create a scroll pane and add the single answer text pane.
        JScrollPane singleAnswerScrollPane =
         new JScrollPane(singleAnswerTextPane);
        // Create a radio button that is associated with the single
        // answer text pane above.
        JRadioButton singleAnswerRadioButton = new JRadioButton();
        // Add the scroll pane and radio button to the panel (for a single
        // answer).
        singleAnswerPanel.add(singleAnswerScrollPane);
        singleAnswerPanel.add(singleAnswerRadioButton);
        // Add the panel holding a single answer to the panel holding
        // all the answers.
        m_allAnswersPanel.add(singleAnswerPanel);
        // Update the display.  m_allAnswersScrollPane is a JScrollPane
        // that has the m_allAnswersPanel (JPanel) as its view.
        m_allAnswersScrollPane.validate();
    }     Sorry for the length of the message, but I really want to solve this problem. So again, when updating the JScrollPane with validate(), the JTextPane for a single answer resizes to it's contents (plain text currently) and loses it's vertical scrollbars, but I want it to stay the same size and maintain the scrollbars.
    Thanks!

    http://java.sun.com/docs/books/tutorial/uiswing/mini/layout.htmlimport javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Test extends JFrame {
        int cnt=0;
        Random r = new Random();
        String[] nouns = {"air","water","men","idjits"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        JScrollPane mainScroll = new JScrollPane(mainPanel);
        JScrollBar mainScrollBar = mainScroll.getVerticalScrollBar();
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JLabel("QuizMaster 2003"), BorderLayout.NORTH);
         content.add(mainScroll, BorderLayout.CENTER);
         JButton jb = new JButton("New");
         content.add(jb, BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              JPanel questionPanel = new JPanel(new GridBagLayout());
              questionPanel.add(new JLabel("Question "+cnt++),
                   new GridBagConstraints(0,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              questionPanel.add(new JLabel("Why is there "+
                            nouns[r.nextInt(nouns.length)]+"?"),
                   new GridBagConstraints(1,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              JTextArea jta = new JTextArea();
              JScrollPane jsp = new JScrollPane(jta);
              jsp.setPreferredSize(new Dimension(300,50));
              questionPanel.add(jsp, new GridBagConstraints(0,1,2,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.BOTH,
                        new Insets(1,2,1,2),0,0));
              mainPanel.add(questionPanel, new GridBagConstraints(0,cnt,1,1,0.0,0.0,
                            GridBagConstraints.EAST,GridBagConstraints.NONE,
                            new Insets(0,0,0,0),0,0));
              mainPanel.revalidate();
              mainScroll.getViewport().setViewPosition(new Point(0, mainPanel.getHeight()));
         setSize(400,300);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • Adding JScrollPane to CardLayout

    public static void panelLayout (String panel)
            cardPanel.add (Rosters.rosterPanel1, "roster1");
            cardPanel.add (Rosters.rosterPanel2, "roster2");
            cardPanel.add (OP300.evalLoadPane1, "op300load1"); // JScrollPane with JPanel inside
            cardPanel.add (mainPanel, "main");
            CardLayout showPanel = (CardLayout)(cardPanel.getLayout ());
            showPanel.show (cardPanel, panel);
        }I'm trying to add a JScrollPane to my CardLayout just like I have with the other JPanels. All of the other JPanels work fine, but adding the JScrollPane is giving me issues. As soon as PanelLayout() is called, even if it isn't calling for the JScrollPane, I'm getting: Exception occurred during event dispatching:
    java.lang.NullPointerException
            at java.awt.Container.addImpl(Container.java:1027)
            at java.awt.Container.add(Container.java:903)
            at HubEvals.panelLayout(HubEvals.java:540)
            at Login.b_loginActionPerformed(Login.java:175)
            at Login.access$000(Login.java:18)
            at Login$1.actionPerformed(Login.java:92)
            ...The JScrollPane modifier is public static so it isn't having problems getting access to it. I even tried putting the JScrollPane inside a JPanel so it would be like:
    - JPanel
    ----- JScrollPane
    ---------- JPanel (panel that is longer than the frame itself, hence why it's in a scroll pane)
    I still got the same error.

    This time I remembered to initialize it. I added it to my initComponents() method and I was still getting the problem:public HubEvals ()
            initComponents ();
            new Rosters ();
            new OP300 ();
            RegisterLogin intro = new RegisterLogin ();
            intro.showInDialog (this);
        }I had accidentally typed new OP3O0 (); instead of new OP300 ();. What's up with that? The first thing I typed doesn't even exist as a method, class, or variable and it still passed NetBeans validation. I spent well over 50 minutes on a stupid '0' being an 'O' and the 2 characters look exactly the same in the code font.
    Anyway, thanks. Problem solved. Heh. You run into stuff like this when you don't leave the computer for hours at a time.

  • Getting Visible text - JTextPane in a JScrollPane

    I have a JTextPane wrapped in a JScrollPane. I want to be able to get the text that is visible at any given time. I want JUST the text that is visible, not the entire text of the document.
    The method to use is obviously getText(int offset, int length), which is from JTextComponent.
    I am wondering how I can retrieve the given offset (ie. the position of the very first visible character) and length (ie. the ending position of the last visible character minus the position of the starting character) from either the JScrollPane or the JTextPane.
    I believe that this might be a rather complex problem as I'm qutie certain I am going to have to manually compute a few things by using several different views.
    Any help anyone could offer would be most appreciated.

    Hi camickr
    I got the JScrollPane now thanks.
    Now I'm still confused on how to solve the original problem.
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    public class TestJTextPane extends JTextPane implements ComponentListener{
          public static void main (String args[]){
               JFrame mainFrame = new JFrame();
               mainFrame.setSize(500,300);
               mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               mainFrame.getContentPane().add(new JScrollPane(new TestJTextPane()));
               mainFrame.setVisible(true);
          public TestJTextPane(){
                this.addComponentListener(this);
          private void viewVisibleText(){
               int offSet = 0;
               int length = 0;
               try{
                    JScrollPane scrollPane = (JScrollPane) this.getParent().getParent();
                    System.out.println(scrollPane.getViewport().getVisibleRect());
                    System.out.println(this.viewToModel(scrollPane.getViewport().getVisibleRect().getLocation()));
               catch (Exception e){
                    e.printStackTrace();
         public void componentResized(ComponentEvent arg0) {
              viewVisibleText();
         public void componentMoved(ComponentEvent arg0) {
              viewVisibleText();
         public void componentShown(ComponentEvent arg0) {
         public void componentHidden(ComponentEvent arg0) {
              // TODO Auto-generated method stub
    }If you run this, you will see that the Rectangle for the getVisibleRect() does not changed, and the call to viewToModel will always return 0.
    Can you please point out where I'm going wrong.
    Thanks for the help

  • Adding JScrollPane on JPanel??Is there any problem.??

    hi,
    I have a JPanel over which i added a JScrollPane on to whose view portvie i added a JTable.
    But the problem is the table is not getting visble.Not only table all the components i add to scrollpane which on a panel is not getting displayed.
    Am i missing something??
    final JScrollPane scrollPane = new JScrollPane();
              panel.add(scrollPane);
              table = new JTable();
              scrollPane.setViewportView(table);

    Make sure to add the panel to the content pane as well.
    If the problem still persists, then please post a simple executable demo program that demonstrates the behavior.

  • Problem in Adding Panel to JScrollPane

    I have added a JScrollPane to the Frame which has GridbagLayout.For JScrollPane,I added one panel.I set the background color of Panel as white.But I am unable to get the white color.I tried by changing background color of JScrollPane also.Still I am unable to get the white color.I set the size of panel as (3000,300) then also I am not getting scroll bars.
    If anybody worked on JScrollpane Please help me.
    Thanks in advance
    Vattikuti

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test extends JFrame {
        public Test() {
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Container content = getContentPane();
         content.setLayout(new GridBagLayout());
         JPanel myPanel = new JPanel();
         myPanel.setBackground(Color.white);
         myPanel.setPreferredSize(new Dimension(500,500));
         myPanel.setBorder(BorderFactory.createTitledBorder("Hello"));
         content.add(new JScrollPane(myPanel), new GridBagConstraints(0,0,1,1,1.0,1.0,
                   GridBagConstraints.EAST, GridBagConstraints.BOTH,
                   new Insets(2,2,2,2),0,0));
         setSize(200,200);
         show();
        public static void main(String[] args) { new Test(); }
    }

  • Removing a window and adding a new one with swing.

    Hi,
    A friend of mine recently asked me to add a GUI for a small chat he made, so I thought I'd help him out. I've come across something that's troubled me in the past, and I could never find a solution. What I'm trying to do is make it so a log in window pops up (have that working alright) and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    Here's an SSCCE example:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.ListSelectionModel;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingUtilities;
    public class Gui extends JFrame {
         public static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
         public String sessionId;
         public int returnCode;
         public boolean recievedReturnCode;
         public boolean errorConnecting;
         public long lastActionDelay;
         private JScrollPane listScrollPane;
         private JList list;
         private JTextPane console;
         private JButton signInButton;
         private JScrollPane consoleScrollPane;
         private JTextField typingField;
         private DefaultListModel userList;
         private JButton sendButton;
         public static void main(String[] args) {
              try {
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             new Gui().setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         public Gui() {
              setResizable(false);
              setSize(500, 500);
              consoleScrollPane = new JScrollPane();
              console = new JTextPane();
              typingField = new JTextField();
              userList = new DefaultListModel();
              sendButton = new JButton();
              initializeLoginWindow();
              setDefaultCloseOperation(EXIT_ON_CLOSE);
         public void initializeLoginWindow() {
              setTitle("Login");
              signInButton = new JButton("Sign in");
              signInButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt) {
                        initializeChatWindow();
              signInButton.setBounds(5, 100, 75, 20);
              getContentPane().add(signInButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
         public void initializeChatWindow() {
              consoleScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              consoleScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              consoleScrollPane.setViewportView(console);
              consoleScrollPane.setBounds(5, 5, 575, 350);
              console.setEditable(false);
              typingField.setEditable(true);
              typingField.setBounds(5, 360, 575, 25);
              list = new JList(userList);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.setSelectedIndex(0);
            list.setVisibleRowCount(5);
            listScrollPane = new JScrollPane(list);
              listScrollPane.setBounds(585, 5, 110, 350);
              sendButton.setText("Send");
              sendButton.setBounds(585, 360, 111, 25);
              getContentPane().add(consoleScrollPane);
              getContentPane().add(typingField);
              getContentPane().add(listScrollPane);
              getContentPane().add(sendButton);
              getContentPane().setLayout(new BorderLayout());
              getContentPane().add(new JPanel());
    }Thanks in advanced!

    jduprez wrote:
    I've come across something that's troubled me in the past, and I could never find a solutionWhat is the problem?
    a log in window pops up (have that working alright)
    and then when you press sign in, it removes that window (log in) and adds the main chat window (have this fully functional, too).Hum, between what is working alright and what is already functional, I fail to see what is missing. Again, what is your problem/question?
    If someone could provide an example or point me in the direction of the proper API to look into, so that I don't have to look through them all, I'd be extremely grateful.
    [url http://download.oracle.com/javase/tutorial/uiswing/components/frame.html]JFrames and [url http://download.oracle.com/javase/tutorial/uiswing/components/dialog.html]dialogs seem to show enough API usage to do that. Still, I stronlgy encourage you to read the whole Swing tutorial: http://download.oracle.com/javase/tutorial/uiswing/index.html
    Incase you didn't see the hyperlink above, here's the SSCCE link: http://www.mediafire.com/?e5e3ci3kbvickla
    The "S" in SSCCE stands for "Short" (or, depending on authors, "Simple"). Anyway, a decent SSCCE should fit within a forum post (between code tags please). The whole idea is to provide the simplest thing to people willing to help. No doubtful sites. No non-standard extensions.
    Best regards,
    The problem is that I cannot seem to remove the first pane, leaving the second one to be drawn on the current one.
    In reguards to SSCCE, I always thought it was just a short runnable class example, but I've added the class to the main post. I'll take a look at the API in a few as well.

  • Paint() method is in infinite loop when focus is set to JTextPane

    Hi All,
    I am creating one JScrollPane, JPanel and JTextPane. JPanel is added to JScrollPane and JTextPane is added to JPanel. If I override paint() method in JPanel, its in infinite loop. I don't know why it is behaving like this. Can anyone solve my problem. Since, I am doing so much drawings in paint() method, its getting to slow.
    Here is the code what I wrote.
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestTextPane1 extends JFrame {
         JPanel panel;
         JScrollPane pane;
         public TestTextPane1() {
              panel = new JPanel(new BorderLayout()) {
                   public void paint(Graphics g) {
                        super.paint(g);
                        System.out.println("inside paint");
              JTextPane textPane = new JTextPane();
              panel.add(textPane);
              pane = new JScrollPane(panel);
              getContentPane().add(pane);
              setSize(300, 200);
              setVisible(true);
         public static void main(String [] args) {
              new TestTextPane1();
    Any help will be useful for me.
    Regards
    Kishore.

    What are you trying to do? You are adding the textPane to the panel and then overriding the paint() method. The textPane will never be painted if you do this.
    In Swing, you should override the paintComponent() method, not the paint() method. See the Swing tutorial on Painting:
    http://java.sun.com/docs/books/tutorial/uiswing/overview/draw.html
    Don't forget to read the "Working With Graphics" link at the bottom.

  • Is caret positioning in right-to-left oriented jtextpane corruptable?

    Dear all -
    Below is a serious problem. I hope I can get help from you experts out there; otherwise, I think it is a bug that should be reported to the JDK developers.
    I am writing an editor using my own keyboard layout to type in Arabic. To do so, I use jTextPane, and my own implementation of DocumentFilter (where I map English keys to Arabic letters). I start by i) setting the component orientation of jTextPane to be from RIGHT_TO_LEFT, and ii) attaching a caretListener to trace the caret's position.
    The problem (I think it is a bug just like what is recorded here: http://bugs.adobe.com/jira/browse/SDK-16315):
    Initially as I type text in Arabic, there is one-to-one correspondence between where I point my mouse and where the caret displays, basically, the same place. However, a problem occurs (and can always be re-produced) when I type a word towards the end of the line, follow it by a space character, and that space character causes the word to descend to the next line as a result of a wrap-around. Now, as I point my mouse to that first line again, the location where I click the mouse and the location where the caret flashes are no longer coincident! Also, the caret progression counter is reversed! That is, if there are 5 characters on Line 1, then whereas initially the caret starts from Position 0 on the right-hand side and increases as more text is added from right to left, it is now reversed where the the caret now increases from left to right for the first line, but correctly increases from right to left in the second line! yes funny stuff and very hard to describe to.
    So, here is an example. I wrote the code below (JDK1.6_u10, on Netbeans 6.5 RC2) to make it easy to reproduce the problem. In the example, I have replaced the keys A, S, D, F and G with their Arabic corresponding letters alif, seen, daal, faa and jeem. Now, type these letters inside the double quotes (without the double quotes) including the two spaces please and watch out for the output: "asdfg asdfg ". Up until you type the last g and before you type space, all is perfect, and you should notice that the caret position correctly moves from 0 upwards in the printlines I provided. When you type that last space, the second word descends as a result of the wrap-around, and hell breaks loose! Notice that whereas the mouse and caret position are coincident on the second line, there is no way to fine-control the mouse position on the first line any more. Further, whereas adding text on the second line is intuitive (i.e., you can insert more text wherever you point your mouse, which is also where the caret would show up), for the first line, if you point the mouse any place over the written string, the caret displays in a different place, the any added text is added in the wrong place! All this because the caret counter is now reversed, which should never occur. Any ideas or fixes?
    Thank you very much for reading.
    Mohsen
    package workshop.onframes;
    import java.awt.ComponentOrientation;
    import java.awt.Rectangle;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    public class NewJFrame1 extends javax.swing.JFrame {
    public NewJFrame1() {
    initComponents();
    jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    CaretListener caretListener = new CaretListener() {
    public void caretUpdate(CaretEvent e) {
    int dot = e.getDot();
    int mark = e.getMark();
    if (dot == mark) {
    try {
    Rectangle cc = jTextPane1.modelToView(dot);
    System.out.println("Caret text position: " + dot +
    ", view location (x, y): (" + cc.x + ", " + cc.y + ")");
    } catch (BadLocationException ble) {
    System.err.println("CTP: " + dot);
    } else if (dot < mark) {
    System.out.println("Selection from " + dot + " to " + mark);
    } else {
    System.out.println("Selection from " + mark + " to " + dot);
    jTextPane1.addCaretListener(caretListener);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane3 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
    jTextPane1.setAutoscrolls(false);
    jTextPane1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jTextPane1KeyTyped(evt);
    jScrollPane3.setViewportView(jTextPane1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jTextPane1KeyTyped(java.awt.event.KeyEvent evt) {
    if (evt.getKeyChar() == 'a') {
    evt.setKeyChar('\u0627');
    } else if (evt.getKeyChar() == 's') {
    evt.setKeyChar('\u0633');
    } else if (evt.getKeyChar() == 'd') {
    evt.setKeyChar('\u062f');
    } else if (evt.getKeyChar() == 'f') {
    evt.setKeyChar('\u0641');
    } else if (evt.getKeyChar() == 'g') {
    evt.setKeyChar('\u062c');
    public
    static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame1().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
    }

    Hi Mohsen,
    I looked at it and indeed, I see what you describe. Sorry, but I can't shed any light. I tried to figure out what software component, or combination of components, is the cause of the problem. I see several candidates:
    1) The JTextPane
    2) The Document
    3) RTL support
    4) BIDI support
    5) Interpretation (by any other software component) of the left and right arrow key
    6) The font
    To clarify number 6: I know virtually nothing of Arabic language (apart from it being written from right to left). I remember however that the actual representation of a letter is dependent of its position between other letters: front, middle and end. What I see to my astonishment is that it seems that the rendering is also aware of this phenomenon. When you insert an A between the S and D of ASDFG, the shape of the S changes. Quite magic.
    I tried to add a second textpane with the same Document, but a different size, to see what would happen with number one if one types text in number two and vice versa.
    In my first attempt, the font that you set on textpane one was gone after I set its document to number two. For me that is very strange. The font was set to the textpane, not to the document. The separation betweem Model and View seems not very clear in this case. So I now also set that font on the second textpane.
    I will post the changed code so that you may experiment some more and hopefully will find the problem.
    You might be interested in a thread on java dot net forums that discusses a memory leak for RTL [http://forums.java.net/jive/message.jspa?messageID=300344#300344]
    Piet
    import java.awt.ComponentOrientation;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    public class NewJFrame1 extends JFrame {
        private static final long serialVersionUID = 1L;
        public NewJFrame1() {
         initComponents();
         // jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         this.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         CaretListener caretListener = new CaretListener() {
             public void caretUpdate(CaretEvent e) {
              int dot = e.getDot();
              int mark = e.getMark();
              if (dot == mark) {
                  try {
                   Rectangle cc = jTextPane1.modelToView(dot);
                   System.out.println("Caret text position: " + dot
                        + ", view location (x, y): (" + cc.x + ", "
                        + cc.y + ")");
                  } catch (BadLocationException ble) {
                   System.err.println("CTP: " + dot);
              } else if (dot < mark) {
                  System.out.println("Selection from " + dot + " to " + mark);
              } else {
                  System.out.println("Selection from " + mark + " to " + dot);
         jTextPane1.addCaretListener(caretListener);
        private KeyAdapter toArabic = new KeyAdapter() {
         public void keyTyped(KeyEvent evt) {
             jTextPane1KeyTyped(evt);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        // @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
         jScrollPane3 = new JScrollPane();
         jTextPane1 = new JTextPane();
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         jTextPane1.setFont(new Font("Tahoma", 0, 24)); // NOI18N
         jTextPane1.setAutoscrolls(false);
         jTextPane1.addKeyListener(toArabic);
         jScrollPane3.setViewportView(jTextPane1);
         GroupLayout layout = new GroupLayout(getContentPane());
         getContentPane().setLayout(layout);
         layout.setHorizontalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.DEFAULT_SIZE, 159,
                   Short.MAX_VALUE).addContainerGap()));
         layout.setVerticalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.PREFERRED_SIZE, 85,
                   GroupLayout.PREFERRED_SIZE).addContainerGap(
                   GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
         pack();
        }// </editor-fold>
        private void jTextPane1KeyTyped(KeyEvent evt) {
         if (evt.getKeyChar() == 'a') {
             evt.setKeyChar('\u0627');
         } else if (evt.getKeyChar() == 's') {
             evt.setKeyChar('\u0633');
         } else if (evt.getKeyChar() == 'd') {
             evt.setKeyChar('\u062f');
         } else if (evt.getKeyChar() == 'f') {
             evt.setKeyChar('\u0641');
         } else if (evt.getKeyChar() == 'g') {
             evt.setKeyChar('\u062c');
        public static void main(String args[]) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
              final NewJFrame1 frameOne = new NewJFrame1();
              frameOne.setLocationRelativeTo(null);
              frameOne.setVisible(true);
              EventQueue.invokeLater(new Runnable() {
                  public void run() {
                   Document doc = frameOne.jTextPane1.getDocument();
                   JTextPane textPane2 = new JTextPane();
                   textPane2.setFont(new Font("Tahoma", 0, 24)); // NOI18N
                   textPane2.setAutoscrolls(false);
                   textPane2.setDocument(doc);
                   textPane2.addKeyListener(frameOne.toArabic);
                   JFrame frameTwo = new JFrame();
                   frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frameTwo.add(new JScrollPane(textPane2));
                   frameTwo.setSize(400, 300);
                   frameTwo.setLocationByPlatform(true);
                   frameTwo.setVisible(true);
                   frameTwo
                        .applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        // Variables declaration - do not modify
        private JScrollPane jScrollPane3;
        private JTextPane jTextPane1;
        // End of variables declaration
    }

Maybe you are looking for

  • Need some help about i18n on Redhat 71. with Oracle 8.1.7

    Initally I used Redhat 7.0 with Oracle 8.1.7, everything had worked find until I upgrade my system to Redhat 7.1. I have no idea about Redhat locate setting. Well, I use NLS_LANG=TRADITIONAL CHINESE_TAIWAN.ZHT16BIG5 to inital database . some characte

  • Adobe Reader X (10.1.2) installation error in windows 7

    Hi I am getting the following error while trying to install the adobe reader x 10. For you information I tried downloading file and installing it using chrome,firfox and IE8 but nothing seems to working. I have also tried disabling my avast AV and tr

  • Reports iview (no link display when using mss id)

    Hi experts, I try to add new reports to MSS Reports Iview I have configured the reports in SPRO ->Personnel Management -> Manager's Desktop -> Enhancement of Function Codes -> Define Function Codes,Define Object Type_Specific Function Codes, and Defi

  • Is Photoshop CS6 Beta works in Windows 8 Consumer Preview?

    Is Photoshop CS6 Beta works in Windows 8 Consumer Preview?

  • FindClass returning NULL

    Hi, I have a servlet deployed in Tomcat (v5.0.12) that invokes a C++ DLL written by me. Some other Java classes that are used by my Servlet are stored in a folder C:\MyClasses (in a package called com.batra.amit). The folder C:\MyClasses is in Tomcat