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.

Similar Messages

  • JTabbedPane and JScrollPane problem

    Hi all,
    I'm trying to make working JScrollPane into JTabbedPane. I have been trying several times to make it but with no acceptable effects :( I attached below the simple code to show what I'm interested in.
    PANEL1 has its dimension. I'd like to make that the JScrollPane will be active and enabled to roll when user change JFrame size to less than PANEL1 on pane1.
    Please help!
    Thanks for everyone,
    Greetings,
    import java.lang.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Sample     {
    static JFrame fr;
    static JPanel pane1, pane2, pane3;
    static JLabel AAA, BBB, CCC;
    static JPanel PANEL1;
    static JTabbedPane panel;
    public static void main(String args[])     {
              fr = new JFrame("Sample");
              pane1 = new JPanel();
              pane1.setLayout(null);
              pane2 = new JPanel();
              pane2.setLayout(null);
              pane3 = new JPanel();
              pane3.setLayout(null);
              panel = new JTabbedPane();
              Font myfont1 = new Font("SansSerif",0,20);
              Font myfont2 = new Font("SansSerif",0,15);
              Font myfont3 = new Font("SensSerif",1,15);
              AAA = new JLabel("AAA");
              BBB = new JLabel("BBB");
              CCC = new JLabel("CCC");
              AAA.setFont(myfont2);
              BBB.setFont(myfont2);
              CCC.setFont(myfont2);
              AAA.setBounds(20,20,300,20);
              BBB.setBounds(20,50,300,20);
              CCC.setBounds(20,80,300,20);
              PANEL1 = new JPanel();
              PANEL1.setLayout(null);
              PANEL1.setBackground(java.awt.Color.CYAN);
              PANEL1.setBounds(20,15,250,300);
              PANEL1.add(AAA);
              PANEL1.add(BBB);
              PANEL1.add(CCC);
              pane1.add(PANEL1);
              panel.insertTab("A", null, pane1, null, 0);
              panel.setSelectedIndex(0);
              panel.insertTab("B", null, pane2, null, 1);
              panel.setSelectedIndex(0);
              panel.insertTab("C", null, pane3, null, 2);
              panel.setSelectedIndex(0);
              panel.setBounds(0,0,550,450);
              fr.setLayout(null);
              //fr.setResizable(false);
              fr.setBackground(java.awt.Color.CYAN);
              fr.setForeground(java.awt.Color.CYAN);
              fr.add(panel);
              fr.pack();
              fr.setSize(550, 450);
              fr.setLocationRelativeTo(null);
              fr.setVisible(true);
    }

    Unfortunately no :( Besides, I can't understand at
    all this line:
    JTabbedPane (panel)TabbedPane = ... new
    w JTabbedPane(...).add/insertTab( ... new
    JScrollPane(new JPanel(...)) ... )It's to big cut-off like for me. Can you insert it
    into my Sample?
    Regards and thanks,It's only my "dev speak". Put a ";" and a var name (, ...) whereever needed, and remove some"()".
    (Sorry, normally I don't help dev beginners on so more complex problems, with just an easy answer.)

  • JTree and JScrollPane problems

    Hello all.
    bear with me a second, so I can explain what is happenning with my code. I have got a java application that is accessing an SQL database (either Oracle or postgreSQL) and inputing the data into a tree.
    More specifically it takes the "enrollment" data and draws into the scrollpane the courses and students enrolled. Everything seems to be working perfectly with the building of the tree.
    but I have a drop down list that can select which years to display (1-4th year). I want the tree in the scrollPane to update when u change the year in the drop down list.
    I have added an ActionListener to the drop down list and it picks up the right selection, and I create a new tree object with the new year details and nothing is changed in the scrollpane.
    This is what the GUI looks like:
    This is my tree class which creates teh tree and adds it to the scrollPane object:
    package Interface;
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.sql.*;
    import Database.Database;
    public class Tree{
         JTree tree;
         JScrollPane scrollPane;
         public Tree(GridBagConstraints c, Container contentPane, GridBagLayout gridBag, int year){
              //Set up the default table.
              TreeNode root = buildTree("Enrollments", year);
              tree = new JTree(root);
              //Set up a scrollPane for the tree.
              scrollPane = new JScrollPane(tree);
              //Set constraints for the ScrollPane
              c.fill = GridBagConstraints.BOTH;
              c.weightx = 1;
              c.weighty = 1;
              c.gridwidth = 2;
              c.gridx = 0;
              c.gridy = 1;
              c.anchor = GridBagConstraints.CENTER;
              gridBag.setConstraints(scrollPane, c);
              contentPane.add(scrollPane);     
              //Set defaults for teh Tree object.
              tree.expandRow(0);
              tree.setRootVisible(false);
              tree.setEditable(true);     
         public DefaultMutableTreeNode buildTree(String s, int year){
              //Set root of tree.
              DefaultMutableTreeNode node = new DefaultMutableTreeNode(s);
              //Create a database object.
              Database db = new Database();
              //change this bit to get the name's of the courses and add into array.
              ResultSet className = db.query("SELECT name FROM courses WHERE year = "+year);
              DefaultMutableTreeNode course = null;
              DefaultMutableTreeNode name = null;
              try {
                        while(className.next()){
                             String classStr = className.getString("name");
                             course = new DefaultMutableTreeNode(classStr);
                             node.add(course);
                             ResultSet firstName = db.query("SELECT students.name FROM students, enrollments, courses WHERE students.id = enrollments.studentID AND enrollments.courseid = courses.id AND courses.name = '"+classStr+"'");
                             while(firstName.next()){
                                  String nameStr = firstName.getString("name");
                                  name = new DefaultMutableTreeNode(nameStr);
                                  course.add(name);
                   catch(Exception e){
                        System.err.println("" + e.getMessage());
                        e.printStackTrace(System.err);
              return node;
    }This is the GUI class that calls on the tree class and draws the GUI. and the actionlistener for the drop down list.
    package Interface;
         import java.awt.*;
         import javax.swing.*;
         import java.awt.event.*;
    import java.sql.*;
         public class GUI extends JFrame implements ActionListener{
              private static final long serialVersionUID = 1L;     
              DropDownMenu yearDrop;
              ScrollPane scrollPane;
              JMenuItem menuItemSave;
              JMenuItem menuItemQuit;
              JMenuBar menuBar;
              JMenu menu;
              JButton save;
              JButton quit;
              Tree tree;
              String year[] = { "First Year", "Second Year", "Third Year", "Fourth Year" };
              Container contentPane = getContentPane();
              GridBagLayout gridBag = new GridBagLayout();
              GridBagConstraints c = new GridBagConstraints();
              public GUI(){
                   setSize(500,500);
                   setTitle("UTAS Enrollments");
                   contentPane.setLayout(gridBag);          
                   save = new JButton("Save");
                   quit = new JButton("Quit");
                   menuItemSave = new JMenuItem("Save");
                   menuItemQuit = new JMenuItem("Quit");
                   menuItemSave.setMnemonic('s');
                   menuItemQuit.setMnemonic('q');
                   yearDrop = new DropDownMenu(year, c, contentPane, gridBag);
                   tree = new Tree(c, contentPane, gridBag, 1);
                   menuBar = new JMenuBar();
                   menu = new JMenu("File");
                   menu.setMnemonic('f');
                   menuBar.add(menu);
                   menu.add(menuItemSave);
                   menu.add(menuItemQuit);
                   setJMenuBar(menuBar);
                   //Set constraints for the Save button
                   c.fill = GridBagConstraints.NONE;
                   c.weightx = 1;
                   c.weighty = 0;
                   c.gridwidth = 1;
                   c.gridx = 0;
                   c.gridy = 2;
                   c.anchor = GridBagConstraints.WEST;
                   save.setMnemonic('s');
                   gridBag.setConstraints(save, c);
                   contentPane.add(save);
                   //Set constraints for the Quit button
                   c.fill = GridBagConstraints.NONE;
                   c.weightx = 1;
                   c.weighty = 0;
                   c.gridwidth = 1;
                   c.gridx = 1;
                   c.gridy = 2;
                   c.anchor = GridBagConstraints.EAST;
                   quit.setMnemonic('q');
                   gridBag.setConstraints(quit, c);
                   contentPane.add(quit);
                   //Add ActionListener to the interactive buttons on the GUI.
                   //QUIT MENU
                   menuItemQuit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             quitAction();
                   //SAVE MENU
                   menuItemSave.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent e){
                             saveAction();
                   //QUIT BUTTON
                   quit.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                             quitAction();
                   //SAVE BUTTON
                   save.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                             saveAction();
                   //DROPDOWN LIST
                   yearDrop.dropDown.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                             listAction();
              public void listAction(){
                   System.out.println("getSelected: "+ year[yearDrop.getSelected()]);
                   tree = new Tree(c, contentPane, gridBag, (yearDrop.getSelected()+1));
                   repaint();
         I have taken out the quitAction and saveAction methods to save space.
    I would have thought creating a new Tree object over the original tree would have updated the scrollPane.
    Any ideas would be awesome.
    Thanks in advance.

    and I create a new tree object with the new year details and nothing is changed in the scrollpane.Creating a new Tree doesn't add the tree to the scroll pane. It just changes the reference of the tree variable to point to the new Tree object. To update the scroll pane you would need to do:
    scrollPane.setViewportView( tree );
    Or another option is to just create a new TreeModel and then change the model that your existing tree is using:
    TreeModel model = new TreeModel(...);
    tree.setModel( model );

  • Problem with JTextPane and StateInvariantError

    Hi. I am having a problem with JTextPanes and changing only certain text to bold. I am writing a chat program and would like to allow users to make certain text in their entries bold. The best way I can think of to do this is to add <b> and </b> tags to the beginning and end of any text that is to be bold. When the other client receives the message, the program will take out all of the <b> and </b> tags and display any text between them as bold (or italic with <i> and </i>). I've searched the forums a lot and figured out several ways to make the text bold, and several ways to determine which text is bold before sending the text, but none that work together. Currently, I add the bold tags with this code: (note: messageDoc is a StyledDocument and messageText is a JTextPane)
    public String getMessageText() {
              String text = null;
              boolean bold = false, italic = false;
              for (int i = 0; i < messageDoc.getLength(); i++) {
                   messageText.setCaretPosition(i);
                   if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && !bold) {
                        bold = true;
                        if (text != null) {
                             text = text + "<b>";
                        else {
                             text = "<b>";
                   else if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        // Do nothing
                   else if (!StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        bold = false;
                        if (text != null) {
                             text = text + "</b>";
                        else {
                             text = "</b>";
                   try {
                        if (text != null) {
                             text = text + messageDoc.getText(i,1);
                        else {
                             text = messageDoc.getText(i, 1);
                   catch (BadLocationException e) {
                        System.out.println("An error occurred while getting the text from the message document");
                        e.printStackTrace();
              return text;
         } // end getMessageText()When the message is sent to the other client, the program searches through the received message and changes the text between the bold tags to bold. This seems as if it should work, but as soon as I click on the bold button, I get a StateInvariantError. The code for my button is:
    public void actionPerformed(ActionEvent evt) {
              if (evt.getSource() == bold) {
                   MutableAttributeSet bold = new SimpleAttributeSet();
                   StyleConstants.setBold(bold, true);
                   messageText.getStyledDocument().setCharacterAttributes(messageText.getSelectionStart(), messageText.getSelectionStart() - messageText.getSelectionEnd() - 1, bold, false);
         } //end actionPerformed()Can anyone help me to figure out why this error is being thrown? I have searched for a while to figure out this way of doing what I'm trying to do and I've found out that a StateInvariantError has been reported as a bug in several different circumstances but not in relation to this. Or, if there is a better way to add and check the style of the text that would be great as well. Any help is much appreciated, thanks in advance.

    Swing related questions should be posted in the Swing forum.
    Can't tell from you code what the problem is because I don't know the context of how each method is invoked. But it would seem like you are trying to query the data in the Document while the Document is being updated. Try wrapping the getMessageText() method is a SwingUtilities.invokeLater().
    There is no need to write custom code for a Bold Action you can just use:
    JButton bold = new JButton( new StyledEditorKit.BoldAction() );Also your code to build the text String is not very efficient. You should not be using string concatenation to append text to the string. You should be using a StringBuffer or StringBuilder.

  • JTextPane/JScrollPane problems

    in my JTextPane i would like to be able to set the tab size (like you can with JTextArea), and for some reason my JScrollPane doesn't want to scroll the JTextPane horizontally, it just wraps the text. any help and sample code is very appreciated.
    TravenE

    Well normally I'd tell you to search the forums because I've answered both of these question several times before. But since the search isn't currently working for me I'm assuming it isn't working for you either, so here are my suggestons.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneTabs extends JFrame
         public TextPaneTabs()
              JTextPane textPane = new JTextPane();
              textPane.setFont( new Font("monospaced", Font.PLAIN, 12) );
              JScrollPane scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
              getContentPane().add( scrollPane );
              setTabs( textPane, 4 );
         public void setTabs( JTextPane textPane, int charactersPerTab)
              FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
              int charWidth = fm.charWidth( 'w' );
              int tabWidth = charWidth * charactersPerTab;
              TabStop[] tabs = new TabStop[10];
              for (int j = 0; j < tabs.length; j++)
                   int tab = j + 1;
                   tabs[j] = new TabStop( tab * tabWidth );
              TabSet tabSet = new TabSet(tabs);
              SimpleAttributeSet attributes = new SimpleAttributeSet();
              StyleConstants.setTabSet(attributes, tabSet);
              int length = textPane.getDocument().getLength();
              textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
         public static void main(String[] args)
              TextPaneTabs frame = new TextPaneTabs();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestNoWrap extends JFrame
         JTextPane textPane;
         JScrollPane scrollPane;
         public TestNoWrap()
              JPanel panel = new JPanel();
              panel.setLayout( new BorderLayout() );
              setContentPane( panel );
              // no wrap by adding text pane to a panel using border layout
              textPane = new JTextPane();
              textPane.setText("1234567890 1234567890 1234567890");
              JPanel noWrapPanel = new JPanel();
              noWrapPanel.setLayout( new BorderLayout() );
              noWrapPanel.add( textPane );
              scrollPane = new JScrollPane( noWrapPanel );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane, BorderLayout.NORTH );
              // no wrap by overriding text pane methods
              textPane = new JTextPane()
                   public void setSize(Dimension d)
                        if (d.width < getParent().getSize().width)
                             d.width = getParent().getSize().width;
                        super.setSize(d);
                   public boolean getScrollableTracksViewportWidth()
                        return false;
              textPane.setText("1234567890 1234567890 1234567890");
              scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane );
         public static void main(String[] args)
              TestNoWrap frame = new TestNoWrap();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • JTextPane and Horizontal Scrollbars

    Hi there,
    I had written an app that included an Event Log, and all was good in my
    world.
    Then one of the app users commented they would like errors to stand out within the log!
    I said "No Problem" but it turns out to be a major bloody headache!!!!!
    I was using a JTextArea but after reading some posts on this forum I decided to use a JTextPane. I found some code for changing the font colour, and everything appeared to be working fine ;-)
    ...until that is I realised my HORIZONTAL_SCROLLBAR_AS_NEEDED was never needed as the text had started to wrap ;-(
    I have tried searching this site and none of the suggestions work for me, the vertical scroll works fine - and I am really stuck. Therefore:
    Is there a way to get the Horizontal scroll bar working in a JTextPane?
    Is there an alternative to JTextPane that will allow me to control font colour by line?
    Do you even know what I am harping on about?
    Or should I admit defeat and add a second JTextArea and a button to switch between my two event types??
    Any suggestions would be greatly received!
    P.S. Below is the edited code that I think is responsible for my problem :0)
    public class EventLogGUI extends JPanel
    private JPanel jpLog = new JPanel();
    private StyledDocument sdLog = new DefaultStyledDocument();
    private JTextPane jtpLog = new JTextPane( sdLog );
    private MutableAttributeSet mas = new SimpleAttributeSet();
    private JScrollPane jspLog;
              public EventLogGUI()
              this.setBounds( 5, 7, 407, 256 );
              this.setBorder( BorderFactory.createLoweredBevelBorder() );
              this.setLayout( null );
              this.add( jpLog );
              jspLog = new JScrollPane( jtpLog,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
              jspLog.setBounds( 12, 25, 372, 180 );
              jpLog.setLayout( null );
              jpLog.setBounds( 5, 5, 397, 218 );
              jpLog.add( jspLog );
              jtpLog.setEditable( false );
              jtpLog.setMargin( new Insets ( 2, 2, 2, 2 ) );
              public void initialiseGUI()
              Vector events = uploadEventLog();
              String event;
              jtpLog.setText( "" );
                        for ( int i = 0; i < events.size(); i++ )
                        event = "" + events.elementAt( i );
                                  if ( event.length() >= 8 && event.substring( 0, 8 ).equals( "WARNING:" ) )
                                            StyleConstants.setForeground( mas, Color.red );
                                  else
                                            StyleConstants.setForeground( mas, Color.black );
                                  try
                                  sdLog.insertString( sdLog.getLength(), event + "\n", mas );
                                  catch( Exception e )
    }

    Hi!
    just wondered if you've searched the forum already. If not: always do that before posting.
    I searched and found this helpful:
    http://forum&threadID=256602
    the solution found in that thread is to extend the JTextPane and add a setLineWrap-method:
    class JTextWrapPane extends JTextPane {
        boolean wrapState = true;
        JTextArea j = new JTextArea();
         * Constructor
        JTextWrapPane() {
            super();
        public JTextWrapPane(StyledDocument p_oSdLog) {
            super(p_oSdLog);
        public boolean getScrollableTracksViewportWidth() {
            return wrapState;
        public void setLineWrap(boolean wrap) {
            wrapState = wrap;
        public boolean getLineWrap(boolean wrap) {
            return wrapState;
    }  now you can use JTextWrapPane instead of JTextPane:
    //  instead of   private JTextPane jtpLog = new JTextPane( sdLog );
        private JTextWrapPane jtpLog = new JTextWrapPane( sdLog );and set JTextWrapPane.setLineWrap(false):
            jtpLog.setLineWrap(false);It may not be the non plus ultra, but it seamed to work for me. ;)

  • JTextPane in JScrollPane... Scrolling when needed

    Hello all.
    I have a jtextpane in a jscrollpane and I'm using the following code to append a line in jtextpane and set the vertical scrollbar of jscrollpane at the bottom...
      htmlDoc = (HTMLDocument) output.getDocument();
      htmlKit.insertHTML(htmlDoc, htmlDoc.getLength(), s, 0, 0, null);
      output.setCaretPosition(htmlDoc.getLength());where output is the jtextpane.
    My problem is that, if the user manually changes the position of the vertical scrollbar, after appending a new line in jtextpane, the above code will set the scrollbar at the bottom.
    Is it possible to keep the scrollbar at the position it was before the new line has been appended (if the position of the scrollbar has been changed)?
    Thanks in advance,
    Charalampos

    StanislavL... with your suggestion the scroll bar will never scroll to the bottom.
    I want to place the scroll bar at the bottom if it was at the bottom before I append text to jtextpane, otherwise I want to leave the scroll bar at the same position it was before I append the text.

  • JTextPane and highlighting

    Hello!
    Here's what I'm trying to do: I have a window that needs to display String data which is constantly being pumped in from a background thread. Each String that comes in represents either "sent" or "recieved" data. The customer wants to see sent and recieved data together, but needs a way to differentiate between them. Since the Strings are being concatinated together into a JTextPane, I need to highlight the background of each String with a color that represents whether it is "sent" (red) or "recieved" (blue) data. Should be easy right? Well, not really...
    Before I describe the problem I'm having, here is a small example of my highlighting code for reference:
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtTest = new JTextPane(doc);
         private Random random = new Random();
         private void appendLong() throws BadLocationException {
              String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
              int start = doc.getLength();
              doc.insertString(doc.getLength(), str, null);
              int end = doc.getLength();
              txtTest.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
         private Color randomColor() {
              int r = intRand(0, 255);
              int g = intRand(0, 255);
              int b = intRand(0, 255);
              return new Color(r, g, b);
         private int intRand(int low, int hi) {
              return random.nextInt(hi - low + 1) + low;
         }As you can see, what I'm trying to do is append a String to the JTextPane and highlight the new String with a random color (for testing). But this code doesn't work as expected. The first String works great, but every subsequent String I append seems to inherit the same highlight color as the first one. So with this code the entire document contents will be highlighted with the same color.
    I can fix this problem by changing the insert line to this:
    doc.insertString(doc.getLength()+1, str, null);With that change in place, every new String gets its own color and it all works great - except that now there's a newline character at the beginning of the document which creates a blank line at the top of the JTextPane and makes it look like I didn't process some of the incomming data.
    I've tried in veign to hack that newline character away. For example:
              if (doc.getLength() == 0) {
                   doc.insertString(doc.getLength(), str, null);
              } else {
                   doc.insertString(doc.getLength()+1, str, null);
              } But that causes the 2nd String to begin on a whole new line, instead of continuing on the first line like it should. All the subsequent appends work good though.
    I've also tried:
    txtTest.setText(txtTest.getText()+str);That makes all the text line up correctly, but then all the previous highlighting is lost. The only String that's ever highlighted is the last one.
    I'm getting close to submitting a bug report on this, but I should see if anyone here can help first. Any ideas are much appreciated!

    It may work but it is nowhere near the correct
    solution.It seems to me the "correct" solution would be for Sun to fix the issue, because it seems they are secretly inserting a newline character into my Document. Here's a compilable program that shows what I mean:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultHighlighter;
    import javax.swing.text.DefaultStyledDocument;
    public class TestFrame extends JFrame {
         private JButton btnAppend = new JButton("Append");
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtPane = new JTextPane(doc);
         private Random random = new Random();
         public TestFrame() {
              setSize(640, 480);
              setLocationRelativeTo(null);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        dispose();
              getContentPane().add(new JScrollPane(txtPane), BorderLayout.CENTER);
              getContentPane().add(btnAppend, BorderLayout.SOUTH);
              btnAppend.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doBtnAppend();
         private void doBtnAppend() {
              try {
                   String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
                   int start = doc.getLength();
                    * This line causes all highlights to have the same color,
                    * but the text correctly starts on the first line.
                   doc.insertString(doc.getLength(), str, null);
                    * This line causes all highlights to have the correct
                    * (different) colors, but the text incorrectly starts
                    * on the 2nd line.
    //               doc.insertString(doc.getLength()+1, str, null);
                    * This if/else solution causes the 2nd appended text to
                    * incorrectly start on the 2nd line, instead of being
                    * concatinated with the existing text on the first line.
                    * (a newline character is somehow inserted after the first
                    * line)
    //               if (doc.getLength() == 0) {
    //                    doc.insertString(doc.getLength(), str, null);
    //               } else {
    //                    doc.insertString(doc.getLength()+1, str, null);
                   int end = doc.getLength();
                   txtPane.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
              } catch (BadLocationException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        new TestFrame().setVisible(true);
         private Color randomColor() { return new Color(intRand(0, 255), intRand(0, 255), intRand(0, 255)); }
         private int intRand(int low, int high) { return random.nextInt(high - low + 1) + low; }
    }Try each of the document insert lines in the doBtnAppend method and watch what it does. (comment out the other 2 of course)
    It wastes resources and is inefficient. A lot of work
    goes on behind the scenes to create and populate a
    Document.I tracked the start and end times in a thread loop to benchmark it, and most of the time the difference is 0 ms. When the document gets to about 7000 characters I start seeing delays on the order of 60 ms, but I'm stripping off text from the beginning to limit the max size to 10000. It might be worse on slower computers, but without a "correct" and working solution it's the best I can come up with. =)

  • 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 and inserting/deleting image

    Hi,
    I have problems with my jtextpane. I am usign jtextpane do make simple richeditor.
    I can insert image, and no problem with inserting
    But after that, where content of jtextpane is saved and opened again, image is not able to delete...
    If is there any solution?
    Sorry for my broken English.

    Hi everyone,
    Does the image get saved when you serialize the document?
    What are you doing to serialize the document by using xml or by serializing it as an object or by using the rtf kit
    Richard West

  • JTextPane inside JScrollPane

    Hi,
    I've seen a lot of possibilities to get a JTextPane into JScrollPane without wraping the text in the forum. None worked for me..
    My situation:
    JTextPane(editable=false) with given text(DefaultStyledDocument) is inside JScrollPane.
    I replace (by pressing a button) some text parts with longer text AND JTextPane wraps it!..
    I tried to set the size of the textPane to the computed line width of the longst line, but nothing happened.. (I expected the JScrollPane to show off horizontal scrollbar, because the width of JTextPane is getting bigger than the width of JScrollPane).
    Anyone knows how to put formatted text into text- or scrollpane without wraping it?
    And who allowed JTextPane to wrap my lines anyway?!
    (it's called StyledDocument and not ChaosDocument :)
    Thanks in advance!
    Raman.

    Not sure that JTextPane is the best place to start. The wrapping is controlled by ParagraphView and its underlying structure. Try looking at implementing extensions to the standard EditorKit/ViewFactory to tweak this behaviour

  • I am not able to launch FF everytime i tr to open it, it says FF has to submit a crash report, i even tried doing that and the report was submitted too, but stiil FF did not start, and the problem still persists, please help me solve this issue in English

    Question
    I am not able to launch FF everytime i try to open it, it says FF has to submit a crash report,and restore yr tabs. I even tried doing that and the report was submitted too, but still FF did not start, and the problem still persists, please help me solve this issue
    '''(in English)'''

    Hi Danny,
    Per my understanding that you can't get the expect result by using the expression "=Count(Fields!TICKET_STATUS.Value=4) " to count the the TICKET_STATUS which value is 4, the result will returns the count of all the TICKET_STATUS values(206)
    but not 180, right?
    I have tested on my local environment and can reproduce the issue, the issue caused by you are using the count() function in the incorrect way, please modify the expression as below and have a test:
    =COUNT(IIF(Fields!TICKET_STATUS.Value=4 ,1,Nothing))
    or
    =SUM(IIF(Fields!TICKET_STATUS=4,1,0))
    If you still have any problem, please feel free to ask.
    Regards,
    Vicky Liu
    Vicky Liu
    TechNet Community Support

  • BOSD, Battery issues and Heating problem after iOS 8 upgrade

    i have upgraded my iPad mini to iOS 8. Ever since I upgraded to iOS 8 am facing blue screen issues and heating problem as well. This is really frustrating even the patch iOS 8.0.2 dint solve the problem. Are you guys listening our complaints. When will you fixing it.

    The same thing happened to me on my 2012 Subaru Outback.  I'm not sure this will help you since you have a Honda, but I'm posting this just in case.
    I paired the audio on my car with my iPhone 6.  However, when I turned the car off and back on again, the iPhone would not pair automatically.  I had to manually connect the iPhone with the car.  Turns out there are two separate bluetooth pairings on my car: one for phone which allows up to 5 devices and one for audio which allows only one device.  So I did the second bluetooth pairing for the phone (had already done the audio), and that fixed it.  YMMV

  • I am making code to try to make a game and my problem is that my code......

    I am making code to try to make a game and my problem is that my code
    will not let it change the hit everytime so im getting the first guy to hit 1 then next hits 8 and so on and always repeats.
    Another problem is that I would like it to attack with out me telling it how much times to attack. I am using Object oriented programming.
    Here is the code for my objects:
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class rockCrab {
         //Wounding formula
         double sL = 70;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 50;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         rockCrab() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              double done = rint(fH - fA);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("Rockcrab hit" +done);
    import java.lang.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.util.Random;
    import static java.lang.Math.*;
    import java.awt.*;
    import java.awt.color.*;
    class self {
         //Wounding formula
         double sL = 1;                                   // my Strength Level
         double bP = 1;                                   // bonus for prayer (is 1 times prayer bonus)
         double aB = 0;                                 // equipment stats
         double eS = (sL * bP) + 3;                         // effective strength
         double bD = floor(1.3 + (eS/10) + (aB/80) + ((eS*aB)/640));     // my base damage
         //Attack formula
         double aL = 1;                                   // my Attack Level
         double eD = 1;                                   // enemy's Defence
         double eA = aL / eD;                              // effective Attack
         double eB = 0;                                   // equipment bonus'
         double bA = ((eA/10) * (eB/10));                    // base attack
         //The hit formula
         double fA = random() * bA;
         double fH = random() * bD;
         double done = rint(fH - fA);
         //health formula
         double health = floor(10 + sL/10 * aL/10);
         self() {
         void attack() {
              health = floor(10 + sL/10 * aL/10);
              fA = random() * bA;
              fH = random() * bD;
              done = rint(fH - fA);
              System.out.println("You hit" +done);
    }Here is the main code that writes what the objects do:
    class fight {
         public static void main(String[] args) {
              self instance1 = new self();
              rockCrab instance2 = new rockCrab();
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
              instance2.health = instance2.health - instance1.done;
              System.out.println("You hit: " +instance1.done);
              System.out.println("rockCrabs health: " + instance2.health);
              instance1.health = instance1.health - instance2.done;
              System.out.println("RockCrab hit: " +instance2.done);
              System.out.println("rockCrabs health: " + instance1.health);
    }when the code is run it says something like this:
    you hit 1
    RockCrabs health is 9
    RockCrab hit 7
    your health is 38
    you hit 1
    RockCrabs health is 8
    RockCrab hit 7
    your health is 31
    you hit 1
    RockCrabs health is 7
    RockCrab hit 7
    your health is 24
    you hit 1
    RockCrabs health is 6
    RockCrab hit 7
    your health is 17
    my point is whatever some one hits it always repeats that
    my expected output would have to be something like
    you hit 1
    RockCrabs health is 9
    RockCrab hit 9
    your health is 37
    you hit 3
    RockCrabs health is 6
    RockCrab hit 4
    your health is 33
    you hit 2
    RockCrabs health is 4
    RockCrab hit 7
    your health is 26
    you hit 3
    RockCrabs health is 1
    RockCrab hit 6
    your health is 20
    Edited by: rade134 on Jun 4, 2009 10:58 AM

    [_Crosspost_|http://forums.sun.com/thread.jspa?threadID=5390217] I'm locking.

  • Remote and IR Problem

    A rather odd and annoying problem has recently been occuring on my MBP. A couple days ago my remote (after working without fail for over a year now) suddenly stopped working. Yesterday night and this morning it started working again but after a while it stopped again. I've read dozens of support articles which haven't really helped because there seems to be another problem.
    Most articles have stated that there is an option to disable the IR receiver in the "security" window under system preferences. When the IR and remote are not working this option disappears but when they are working the option is present. I have also tried replacing the battery without any result.
    I am now thinking that it might have something to do with heat buildup because it is mainly occuring after the laptop has been on for about a half hour, so I am going to try to borrow someone's fan.
    If anyone has any suggestions to solve this I would appreciate it if you could help. Thanks!
    MacBook Pro 1.83 GHz   Mac OS X (10.4.9)  

    check out this thread. Seems to be the same problem.
    http://discussions.apple.com/thread.jspa?messageID=4701905&#4701905

Maybe you are looking for

  • Updated to iOS 7, but only the first page of my app buttons stayed.  How can I get them back?

    I just updated to iOS 7, but only the first page of my app buttons stayed.  How can I get them back?  And how do I show the Apple Music and Weather app- I can find them in spotlight, but there isn't an app button for them.

  • Phone buttons not work when charging

    I have Nokia Lumia 900..   When I hook the phone to the charger, the phone is disabled... you can't push up the wallpaper to use the phone buttons on the start screen.  If you disconnect it from the charger, it works fine.  I have done a hard phone r

  • Check box in bsp page.

    hi experts. i  m new to bsp. i  want to fetch one field from a ztable  with check box may be  possible field  have more than 4 values. checkbox1           .... value1 checkbox2          ..... value2 checkbox3          ..... value3 checkbox4         

  • IDOC Message type suitable for VA32

    Hi, I am trying to investigate the automation of transaction VA32, "Change Schedule agreement ". Information relating to my updates from the customer are now available in an electronic format. I therefore wish to now automate this time consuming job

  • Error occures when i try to download song on ipod

    every time i try downloading a song i get an error and it wont dl to my ipod so i can listen to it