JScrollPane, JTextPane and JPanel... wtf?

i am working on a extending a JPanel to have a JTextPane in a JScrollPane. When i add the JTextPane to the JScrollPane inside of the JPanel object it doesn't scroll horizontally, but when i add the whole panel to a JScrollPane in the JFrame that i have testing it, it does scroll horizontally, the JScrollPane in both instances the JScrollBar has both horizontal and vertical scrolling set to as needed.
why is this happening?

Thanks for your answers!
Revalidating did the trick, however I still have a problem with the JScrollPane... I created a new JScrollPane and wrote so:
myScrollPane = new JScrollPane(internalPanel);
myScrollPane.setPreferredSize(new java.awt.Dimension(2, 205));
myScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//Added Code
handScrollPane.setViewportView(handPanel);
//End Added Code
mainPanel.add(myScrollPane, BorderLayout.SOUTH);Then whenever items were added to the internalPanel I changed the scroll-bar's maximum value to the height of the internalPanel by writing:
myScrollPane.getVerticalScrollBar().setMaximum(internalPanel.getHeight());But when I run my application, the scroll-bar's maximum value doesn't change even though items are added to the internalPanel. Why is this?
With Thanks,
laginimaineb.
B.U.M.P (Sorry)

Similar Messages

  • 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.

  • 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. ;)

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • 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. =)

  • What's difference between JPanel.remove(); and JPanel = null

    nice day,
    how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null,
    1/ because if JPanel does not contain any static JComponents
    2/ or any reference to static objects,
    then works as well as JPanel.remove or JPanel = null,
    or what and why preferred to avoid some action (to avoid to remove or to avoid to null)

    mKorbel wrote:
    nice day,
    how can remove JPanel (including its JComponents), safe way, can you explain the difference between JPanel.remove () and JPanel = null, Remove the JPanel from the container it was part of and make sure you do not keep any references to it from your own classes. Don't make it any more difficult than it has to be.

  • 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.

  • Resizing JFrames and JPanels !!!

    Hi Experts,
    I had one JFrame in which there are three objects, these objects are of those classes which extends JPanel. So, in short in one JFrame there are three JPanels.
    My all JPanels using GridBagLayout and JFrame also using same. When I resize my JFrame ,it also resize my all objects.
    My Problem is how should i allow user to resize JPanels in JFrame also?? and if user is resizing one JPanel than other should adjust according to new size ...
    Plese guide me, how should i do this ...
    Thanknig Java Community,
    Dhwanit Shah

    Hey there, thanx for your kind intereset.
    Here is sample code .
    In which there is JFrame, JPanel and in JPanel ther is one JButton.Jpanel is added to JFrame.
    I want to resize JPanel within JFrame,I am able to do resize JFrame and JPanel sets accroding to it.
    import java.awt.*;
    import javax.swing.*;
    import com.borland.jbcl.layout.*;
    public class FramePanel extends JFrame {
    JPanel contentPane;
    GridBagLayout gridBagLayout1 = new GridBagLayout();
    public FramePanel() {
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    public static void main(String[] args) {
    FramePanel framePanel = new FramePanel();
    private void jbInit() throws Exception {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(gridBagLayout1);
    this.setSize(new Dimension(296, 284));
    this.setTitle("Frame and Panel Together");
    MyPanel myPanel = new MyPanel();
    this.getContentPane().add(myPanel);
    this.setVisible(true);
    class MyPanel extends JPanel {
    public MyPanel() {
    this.setSize(200,200);
    this.setLayout(new FlowLayout());
    this.setBackground(Color.black);
    this.setVisible(true);
    this.add(new JButton("Dhwanit Shah"));
    I think i might explained my problem
    Dhwanit Shah
    [email protected]

  • Inserting a Gui program using JFrames and JPanel

    I'm trying to insert a chat program into a game that I've created! The chat program is using JFrames and JPanels. I want to insert this into a GridLayout and Panel. How can I go about doing this?

    whatever is in the frame's contentPane now, you add to a separate JPanel.
    you also add your chat stuff to the separate panel
    the separate panel is added to the frame as the content pane

  • JScrollpane and JPanel help

    i have a panel which is bigger than the main window's size. i want to add it onto the ScrollPane. but the scrollbar is not working. how do i refresh the scrollbar so that the scrollbar comes when the JPanel is attached onto it.

    the full code is
    public EditorPanel(int flag,String title,EditorFrame ed)
    Toolkit tk=Toolkit.getDefaultToolkit();
    clipBoard=tk.getSystemClipboard();
    write = new JTextPane();
    fileFlag=flag;
    fileName=title;
    edf=ed;
    EditorKit editorKit = new StyledEditorKit()     
    public Document createDefaultDocument()     
    {return new ColorSyntax();
    searchIndex=0;
         // creating the toolbar          
         toolBar=new JToolBar();
         addButtons(toolBar);
         toolBar.setBorder(new SoftBevelBorder(BevelBorder.RAISED));
         toolBar.setFloatable(false);
         toolBar.setBounds(0, 0, 800, 20);
         write.setEditorKitForContentType("text/8085", editorKit);
         write.setContentType("text/8085");
         write.replaceSelection("");
         write.requestFocus();
         write.addKeyListener(this);
         write.registerKeyboardAction(edf.getUndoAction(),KeyStroke.getKeyStroke,KeyEvent.VK_Z,InputEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
         write.registerKeyboardAction(edf.getRedoAction(),KeyStroke.getKeyStroke(KeyEvent.VK_Y,InputEvent.CTRL_MASK),JComponent.WHEN_IN_FOCUSED_WINDOW);
         Dimension d=tk.getScreenSize();
         StyledDocument styledDoc = write.getStyledDocument();
         AbstractDocument doc = (AbstractDocument)styledDoc;
         doc.addUndoableEditListener(new MyUndoableEditListener());
    //problem is here
         scrollpane = new JScrollPane(write);          
         scrollpane.setPreferredSize(new Dimension((2*d.width)/3 - 15,3*d.height/4));
         scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         // making the object of the device panel to be added onto the device scroller
         devAddPanel =new DeviceAddPanel();
         deviceScrollpane = new JScrollPane();
         deviceScrollpane.setViewportView(devAddPanel);
         deviceScrollpane.setPreferredSize(new Dimension((d.width)/3 - 15,3*d.height/4));
         deviceScrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         add(toolBar, BorderLayout.PAGE_START);
         //Create a split pane with the two scroll panes in it.
         splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,deviceScrollpane,scrollpane);
         splitPane.setOneTouchExpandable(true);
         splitPane.setDividerLocation(((d.width)/3)-5);
         splitPane.setContinuousLayout(true);
         splitPane.setDividerSize(15);
         add(splitPane, BorderLayout.CENTER);
    //problem ends here
    i am creating a split pane in which on the left i am adding the device panel which is giving the problem even though the panel is bigger that the scrollpane's size it is not showing the vertical scrollbar. the right side with the text area is working fine

  • JPanel, jScrollPane, jLists and removing components

    I have a method that when a textfield gets the focus, I want my jScrollPane to clear out. I don't want to removeAll, but I only want to remove the 2 jLists: listCheckBox and listDescription.
    What I have below doesn't visually remove my jLists.
    What can I do?
    jScrollPane1.remove(listCheckBox);
    jScrollPane1.remove(listDescription);
    jPanel1.revalidate();
    jPanel1.repaint();

    This is the entire code. It should compile. I don't know if this counts as a SSCCE or not. I am using the JDK 1.5 & Swing Layout Extensions 1.0 libraries. With this code, I have my jScrollPane to clear out correctly. Now, the mouselistener only works every other time the find button is clicked.
    import java.awt.Component;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.Vector;
    import javax.swing.JCheckBox;
    import javax.swing.JList;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListSelectionModel;
    import javax.swing.UIManager;
    * NewJFrame.java
    * Created on November 3, 2006, 11:17 AM
    * @author  a1025667
    public class NewJFrame extends javax.swing.JFrame {
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jScrollPane1.requestFocus();
        /** 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.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextField1 = new javax.swing.JTextField();
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTextField1.addFocusListener(new java.awt.event.FocusAdapter() {
                public void focusGained(java.awt.event.FocusEvent evt) {
                    jTextField1FocusGained(evt);
            jButton1.setText("jButton1");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(131, 131, 131)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(jPanel1Layout.createSequentialGroup()
                            .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 188, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(14, 14, 14)
                            .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 87, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 306, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(166, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(25, 25, 25)
                    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jButton1))
                    .add(63, 63, 63)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 147, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(117, Short.MAX_VALUE))
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addContainerGap())
            pack();
        }// </editor-fold>                       
        private void jTextField1FocusGained(java.awt.event.FocusEvent evt) {                                       
    // TODO add your handling code here:
            Vector listData = new Vector();
            JList emptylistCheckBox = new JList();
            JList emptylistDescription = new JList();
            emptylistCheckBox.setListData(listData);
            emptylistDescription.setListData(listData);
            jScrollPane1.setRowHeaderView(emptylistCheckBox);
            jScrollPane1.setViewportView(emptylistDescription);
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            Vector listData = new Vector();
            listData.add("row1");
            listData.add("row2");
            listData.add("row3");
            listCheckBox.setListData(buildCheckBoxItems(listData.size()));
            listDescription.setListData(listData);
            listCheckBox.setCellRenderer(new CheckBoxRenderer());
            listCheckBox.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            listCheckBox.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent me) {
                    int selectedIndex = listCheckBox.locationToIndex(me.getPoint());
                    if (selectedIndex < 0)
                        return;
                    CheckBoxItem item = (CheckBoxItem)listCheckBox.getModel().getElementAt(selectedIndex);
                    item.setChecked(!item.isChecked());
                    listDescription.setSelectedIndex(selectedIndex);
                    listCheckBox.repaint();
            listDescription.setFixedCellHeight(20);
            listCheckBox.setFixedCellHeight(listDescription.getFixedCellHeight());
            jScrollPane1.setRowHeaderView(listCheckBox);
            jScrollPane1.setViewportView(listDescription);
            jScrollPane1.revalidate();
            jScrollPane1.repaint();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new NewJFrame().setVisible(true);
        private CheckBoxItem[] buildCheckBoxItems(int totalItems) {
            CheckBoxItem[] checkboxItems = new CheckBoxItem[totalItems];
            for (int counter=0;counter<totalItems;counter++) {
                checkboxItems[counter] = new CheckBoxItem();
            return checkboxItems;
        class CheckBoxItem {
            private boolean isChecked;
            public CheckBoxItem() {
                isChecked = false;
            public boolean isChecked() {
                return isChecked;
            public void setChecked(boolean value) {
                isChecked = value;
        class CheckBoxRenderer extends JCheckBox implements ListCellRenderer {
            public CheckBoxRenderer() {
                setBackground(UIManager.getColor("List.textBackground"));
                setForeground(UIManager.getColor("List.textForeground"));
            public Component getListCellRendererComponent(JList listBox, Object obj, int currentindex,
                    boolean isChecked, boolean hasFocus) {
                setSelected(((CheckBoxItem)obj).isChecked());
                return this;
        // Variables declaration - do not modify                    
        private javax.swing.JButton jButton1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                  
        public  JList listCheckBox = new JList();
        public  JList listDescription = new JList();
    }

  • JScrollPane, JTextPane, Weird scrolling happening

    The code below shows the problem I am having: In short, I have a textPane in a scrollPane but when I try to getViewPort.setViewPosition(0,0); then the scroll pane briefly flashes to position 0,0 then re positions itself to display the bottom of the text pane. It is driving me wild! If I removed the InsertString function call used on the Document of the textPane, then it works as I thought it should (apart from an initial glitch where the slider bar is placed near the top...- see example)
    in the example I have a 'tall' JTextPane (ie, lot's of linefeeds) with a red panel all in a JPanel which inturn lies in a JScrollPane. Click on the 'Force Update' button to force the Text pane to be updated (in my real java class, there is other stuff to change the values of the textpane) and to set the display position to 0,0. Notice how the slider button flashes to the top of the vertical bar then returns to the bottom. If you cick on the 'toggle InsetString Active' button, then the code to Insert the String to the textArea is by-passed. Now clicking on the 'Force Update' button (after the initial glitch) does send the view to the top of the Jpanel(which now contains an empty textarea and a red panel).
    Can anyone give any clues as to what is causing the Scroll pane to redraw to the bottom of the panel? (and what is causing the glitch after the toggle InsertString button is pressed?)
    I have tried it on JDK 1.3.1 and 1.4 and scoured the groups for similar problems but found none. Lots have people had prblems getting the JScrollpane to the bottom of the textpane but I can't seem to stop it going down!
    I'd appreciate any help as I'm quickly going bald....
    Marc
    code begins....
    -------------------------cut here--------------------------
    import javax.swing.*;
    import java.awt.*; //for layout managers
    import java.awt.event.*; //for action and window events
    import javax.swing.text.*;
    public class WierdScroll extends JFrame
    ScrollPane scrollPane = null;
    JButton button = null;
    JButton b2 = null;
    JPanel screen = null;
    // below is the style to be associated with the textpane
    static private SimpleAttributeSet normalStyle = new SimpleAttributeSet(StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
    static
    StyleConstants.setFontFamily(normalStyle, "Courier");
    StyleConstants.setFontSize(normalStyle, 12);
    public WierdScroll()
    super("Wierd Scrolling \'feature\'");
    // create and setup the components
    screen = new JPanel();
    scrollPane = new ScrollPane();
    scrollPane.setVerticalScrollBarPolicy(
    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setPreferredSize(new Dimension(250, 155));
    scrollPane.setMinimumSize(new Dimension(10, 10));
    scrollPane.updateConstraintView();
    button = new JButton("Force update");
    button.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    scrollPane.updateConstraintView();
    b2 = new JButton("toggle InsertString Active");
    b2.addActionListener(new java.awt.event.ActionListener()
    public void actionPerformed(ActionEvent e)
    JButton b = (JButton) e.getSource();
    scrollPane.allowInsertString = !scrollPane.allowInsertString;
    scrollPane.updateConstraintView();
    // add the component to the frame
    screen.add(scrollPane);
    screen.add(button);
    screen.add(b2);
    getContentPane().add(screen);
    public static void main(String[] args) {
    JFrame frame = new WierdScroll();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    // this extended class is the scrollpane. The problem occurrs when the doc.insertString function is called;
    // When insertString is called, the scroll pane flicks to the bottom of the scroll view but when insertString
    // is not called then the setViewPostion works OK....
    public class ScrollPane extends JScrollPane
    public JPanel panel;
    public JTextPane margin;
    public boolean allowInsertString = true;
    /** Creates a new instance of ConstraintView */
    public ScrollPane()
    // create the pane
    margin = new JTextPane();
    // create the label
    JPanel jp = new JPanel();
    jp.setBackground(Color.red);
    jp.setPreferredSize(new Dimension(500,500));
    panel = new JPanel();
    panel.setBackground(Color.white);
    // add the label and pane to the panel
    panel.add(margin);
    panel.add(jp);
    // set the scroll voew to be the panel
    setViewportView(panel);
    public void updateConstraintView()
    // if doc has stuff in it, then clear contents
    Document doc = margin.getDocument();
    if (doc.getLength() > 0)
    try
    doc.remove(0, doc.getLength());
    catch (BadLocationException ble) {}
    // the allowInsertString is toggled via button on screen to stop insertString call
    if (allowInsertString)
    try {
    doc.insertString(0, "1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n", normalStyle);
    catch (BadLocationException ble) {}
    // set viewport so that it scrolls to top
    getViewport().setViewPosition(new Point(0,0));

    Cheers!
    using the setCaretPosition() of the JTextPane instead of the getViewport().setViewPosition(new Point(0,0)) method of the JScrollPane works a treat.
    But I would have thought that the scroll pane should have 'complete' control (unless specified by programmer) of what it displays. It seems strange to have a component of a scrollpane dictate to the scrollpane what it should show...
    Thanks for your assistance.
    On a different note, has anyone noticed that the word 'c l a s s' has become cl***?? Is this a victim of sun's new swear filter to go with the new site look?

  • JTextPane and viewports

    Hi,
    I asked this question before but I may have made it too complex a question and may have confused some of you so I'll ask it a little differently.
    Here is what I would like to do. Lets say I define a JTextPane to be 10 inches wide and 10 inches in height, but I would only like the viewable area to be only 5x5 inches wide at a time. I want to be able to view the entire JtextPane, but only in 5" by 5" viewable window. When I get to the far right side, or bottom of the viewable window, the window would then move with my next arrow key press. Can someone tell me if this is possible. I've tried some things with scrollbars and a JScrollpane with no luck. I have to have the ability to stop the user when they reach their 10 inch margin and once I introduce scroll bars, there is no way to stop them at 10 inches. This problem comes from the fact that I want to be able to define a Jtextpane to be larger than the screen size someone is limited too, but I still want to limit it to 10 inches. Any ideas at all???
    Joe Crew

    Denis,
    I thought I would post this as a guide to anyone else having the same problem. Not shown below is where I created a BorderLayout and my own personal toolbar for text editing commands which I added to the "North" border. Here is the pseudocode for creating a JTextPane that you can create at a size larger than your PC screen size, have scrollbars, and still limit the width of the JTextPane area. The paradox was once I turn on scrollbars I could no longer limit the size of the JTextPane. Note that in main() not shown here I specified the application to have a setSize of 640x480.
    <CODE>
    private void setScrollBars() {
    // These next few variables were actually declared in another
    // part of the overall application, I just added them here
    // for the sake of clarity. p1 was used for my toolbar,
    // thus p2 is shown here.
    JPanel p2 = new JPanel();
    JTextPane jpane = new JTextPane();          
    Dimension myDim = new Dimension();
    myDim.setSize(1000, 1000);          
    jpane.setPreferredSize(myDim);
    p2.add(jpane);
    jscroll = new JScrollPane(p2);
    jscroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jscroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    add(jscroll, "Center" );
    </CODE>
    The mistake I made previously, which I am sure could still be fixed by someone, was I added the JTextPane to the JScrollbar, then added the JScrollbar to the JPanel. I could not control the actual size of the JTextPane width or height this way. By adding the JtextPane to the Panel and then adding the panel to the JScrollPane, the panel does all of the scrolling and I can specify the exact size of the JTextPane I want. You also don't have to do any monkey business with moving viewports around this way either.
    One issue yet to be addressed by this method is even though you can't see the text beyond the area you create for the JTextPane, text still gets entered past the horizontal limit. I'm working on that issue as I type this, but I wanted to at least post the main solution before this original post got too outdated.
    joberoni

  • How to add a JScrollPane in a JPanel

    I have a JPanel (layout = null, size = 200*400).
    I would like to add a JScrollPane, that sizes 100*100 and that contains an other JPanel, at the location 0,200 in the first JPanel. I would like too that the JScrollBar is always visible.
    How is it possible ?

    The scrollbars will appear automatically when the preferred size of the panel is greater than the size of the scroll pane. So you probably need to add:
    panel.setPreferredSize(...);
    Of course if you use LayoutManagers, instead of a null layout, then this is done automatically for you.
    If you want the scroll bars to appear all the time then read the JScrollPane API.

  • JScrollPane is smearing JPanel

    When painting to a panel inside a JScrollPane, I am having problems with the panel smearing as I scroll. It looks just as though it's repainting over what was already painted on the panel. Just as some testing, I called repaint within my paint method just to try and determine where the issue was coming from. While this didn't fix the issue nor kill my processor, it did seem to make it a little better. Could this be a problem as to the way I am drawing to the panel, or an issue with my use of the JScrollPane?
    Here is my SongDisplay class that extends a JPanel:
    package gui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import javax.swing.JPanel;
    * @author tlee
    public class SongDisplay extends JPanel implements /*MouseListener,*/ SongDisplayInterface
        List<SongFileWordDisplay> words = Collections.synchronizedList(new ArrayList<SongFileWordDisplay>());
        public SongDisplay()
            super();
            /*this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
              this.addMouseListener(this);*/
        @Override
        public void paint(Graphics g)
            g.setColor(Color.BLACK);
            synchronized (words)
                for (SongFileWordDisplay word : words)
                    g.drawString(word.getLyric(), word.getPoint().x, word.getPoint().y);
        public void setWidth(int width)
            this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
            super.revalidate();
        public synchronized void addSongFileWordDisplay(SongFileWordDisplay sfwd)
            words.add(sfwd);
            this.repaint();
    }

    tristanlee85 wrote:
    When painting to a panel inside a JScrollPane, I am having problems with the panel smearing as I scroll. It looks just as though it's repainting over what was already painted on the panel. Just as some testing, I called repaint within my paint method just to try and determine where the issue was coming from. While this didn't fix the issue nor kill my processor, it did seem to make it a little better. Could this be a problem as to the way I am drawing to the panel, or an issue with my use of the JScrollPane?
    Here is my SongDisplay class that extends a JPanel:
    package gui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import javax.swing.JPanel;
    * @author tlee
    public class SongDisplay extends JPanel implements /*MouseListener,*/ SongDisplayInterface
    List<SongFileWordDisplay> words = Collections.synchronizedList(new ArrayList<SongFileWordDisplay>());
    public SongDisplay()
    super();
    /*this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
    this.addMouseListener(this);*/
    @Override
    public void paint(Graphics g)
    g.setColor(Color.BLACK);
    synchronized (words)
    for (SongFileWordDisplay word : words)
    g.drawString(word.getLyric(), word.getPoint().x, word.getPoint().y);
    public void setWidth(int width)
    this.setPreferredSize(new Dimension(width, GuiConstants.SONG_DISPLAY_HEIGHT));
    super.revalidate();
    public synchronized void addSongFileWordDisplay(SongFileWordDisplay sfwd)
    words.add(sfwd);
    this.repaint();
    It is definetly a problem in your paint--you need to call super.paint(g) as the first thing so your object will be painted correctly before you try to put your twist of the world in there.

Maybe you are looking for

  • Direct sales line items not appearing in VF04 even if MIRO document created

    Hi, Some of the direct sales line item are mysteriously not appearing in VF04, even though the MIRO for the PO related to it is done. In some cases all the items of sales orders are not appearing in VF04 , in some cases it is happening randomly. Such

  • Is flash player 11.3 compatible with Windows vista 64 bit?

    I don't have major issues with the video and sound (the flash player used to crash frequently but that seems to have been resolved). But I can't adjust the volume with the volume control wheel when I watch videos on firefox. When I check volume mixer

  • Combo box list getting widened while selecting

    I have an application , which have combo boxes inside a DIV tag. When the length of one the item in the list box is greater the specified length of the combo box, the display of the list gets widened and the combo box widens to the lengthiest items'

  • Upgrading iTunes from 10.1.2 to 10.5

    I'm trying to upgrade iTunes on my Mac from 10.1.2 to 10.5 and it's not installing. I thought that I would have had the most recent version since my Mac is supposed to automatically tell me when I need to updates something and it doesn't seem to be d

  • Re: In Mac's PAINTR application, what exactly does the "Splash" function do?

    In Mac's PAINTR application, what exactly does the "Splash" function do?  It isn't mentioned in the Toolbox Documentation, but the "Splash" option is given right next to the "Draw" option at the top of the screen in the application itself.