Adjusting JScrollPane

Hello,
I am using JScrollPane,and my problem is that the scroll bar is not moving with the content of the text. Is there a way to configure this?
Cheers,
BuZZZZ...

JScrollPane.setCaretPosition if I'm not wrong

Similar Messages

  • How to make JScrollpane not to fetch data while scrollbar is adjusting?

    how to make JScrollpane not to fetch data while scrollbar is adjusting?
    Hi,
    I need to make the jscrollpane get data only when the scrollbar stops scrolling.
    for instance if I hold the scrollbar's thumb and drag it to pass 1000 records, I want the view to wait until I release the thumb before taking any action( ex. adjust the view). in other words if the value of getValueIsAdjusting() of scrollbar is true, then the jscrollpsne should wait until it changes to false before doing anything. this is the same approach that Outlook takes when browsing through the list of emails in your mailbox.
    I don't know how to solve this issue. any help regarding this issue would be appreciated.
    thanks
    Saba

    You are planning to mention your cross-post(s) somewhere in this post, correct?

  • JScrollPane doesn't adjust itself to the view component

    I have an applet that shows a JPanel in JScrollPane:
    form the applet:
    public void init() {
    getContentPane().setLayout(new BorderLayout());
    panel = new SnapCanvas(); //snapCanvas extends JPanel and is not a Canvas
    drawGraph(graph);
    jScrollPane = new JScrollPane(canvas);
    getContentPane().add(jScrollPane, BorderLayout.CENTER);
    setVisible(true);
    canvas.repaint();
    Now this works fine, but if the JPanel's (called canvas in the code) prefered size is changed the scroll pane doesn't adjust itself. What do I do in order for the JScrollPane to adjust when the JPanel is changed?
    Thanks

    foubd the solution in http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html#sizing

  • Problems putting Adjustment Listener to the JScrollPane

    Can we add an addJustment Listener to the JScrollPane.

    You can add a ChangeListener to the corresponding JViewport. See the JViewport docs.

  • Varying size of JScrollPane

    Hi.
    I hope you can help me figure out what's going on. I have a component that I've written that should display buttons vertically (it's a basis for an OutlookBar styled component).
    The component is based on a JPanel that is put in a JScrollPane and the buttons are added to the JPanel. The JPanel has a VerticalFlowLayout (a custom layout class).
    Now for the problem: Every time I adjust the size of the component so that a scroll bar should appear, the getPreferredSize() method of the JScrollPane returns a width that is lesser than it returns when the scroll bar is not visible! The weird thing is that the difference in the width is exactly the width of the scroll bar... but it doesn't make much sense since the width that is returned when the scroll bar is visible is less than the width that is returned when the scroll bar is not visible (it would make sense to have it the other way around!).
    Since my component needs to keep a consistent width this behavior is extremely annoying! Below you can find the code for the panel (and the needed layout) if you'd like to try this out, any help will be greatly appreciated:
    import javax.swing.*;
    import javax.swing.plaf.ComponentUI;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    * A panel that contains a set of operations that are displayed under a common
    * category name on a <code>OutlookBar</code>.
    * @version Revision:$ Date:$
    public class OutlookBarCategoryPanel extends JPanel
        protected JPanel m_contentPanel = new JPanel( new VerticalFlowLayout( 5 ) );
        private JScrollPane m_contentScrollPane = new JScrollPane( m_contentPanel,
                                                        JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         * Constructs a new <tt>OutlookBarCategoryPanel</tt> that is initially empty.
        public OutlookBarCategoryPanel()
            super( new BorderLayout() );
            m_contentPanel.setBackground( SystemColor.control );
            super.add( m_contentScrollPane, BorderLayout.CENTER );
         * If the <code>preferredSize</code> has been set to a
         * non-<code>null</code> value just returns it.
         * If the UI delegate's <code>getPreferredSize</code>
         * method returns a non <code>null</code> value then return that;
         * otherwise defer to the component's layout manager.
         * @return the value of the <code>preferredSize</code> property
         * @see #setPreferredSize
         * @see ComponentUI
        public Dimension getPreferredSize()
            Dimension size = super.getPreferredSize();
            if( size.width < m_contentScrollPane.getPreferredSize().width )
                size.width = m_contentScrollPane.getPreferredSize().width;
            return size;
         * Appends the specified component to the end of this container.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp   the component to be added
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @return    the component argument
        public Component add( Component comp )
            return m_contentPanel.add( comp );
         * Adds the specified component to the end of this container.
         * Also notifies the layout manager to add the component to
         * this container's layout using the specified constraints object.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp the component to be added
         * @param     constraints an object expressing
         *                  layout contraints for this component
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @see       LayoutManager
         * @since     JDK1.1
        public void add( Component comp, Object constraints )
            m_contentPanel.add( comp );
         * Adds the specified component to this container with the specified
         * constraints at the specified index.  Also notifies the layout
         * manager to add the component to the this container's layout using
         * the specified constraints object.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param comp the component to be added
         * @param constraints an object expressing layout contraints for this
         * @param index the position in the container's list at which to insert
         * the component; <code>-1</code> means insert at the end
         * component
         * @see #addImpl
         * @see #validate
         * @see #revalidate
         * @see #remove
         * @see LayoutManager
        public void add( Component comp, Object constraints, int index )
            m_contentPanel.add( comp, index );
         * Adds the specified component to this container at the given
         * position.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * Note: If a component has been added to a container that
         * has been displayed, <code>validate</code> must be
         * called on that container to display the new component.
         * If multiple components are being added, you can improve
         * efficiency by calling <code>validate</code> only once,
         * after all the components have been added.
         * @param     comp   the component to be added
         * @param     index    the position at which to insert the component,
         *                   or <code>-1</code> to append the component to the end
         * @return    the component <code>comp</code>
         * @see #addImpl
         * @see #remove
         * @see #validate
         * @see #revalidate
        public Component add( Component comp, int index )
            return m_contentPanel.add( comp, index );
         * Adds the specified component to this container.
         * This is a convenience method for {@link #addImpl}.
         * <p>
         * This method is obsolete as of 1.1.  Please use the
         * method <code>add(Component, Object)</code> instead.
         * @see add(Component, Object)
        public Component add( String name, Component comp )
            return m_contentPanel.add( name, comp );
         * Removes the specified button from the panel.  The reference that is sent as
         * a parameter needs to point to the same instance as the button that should actually
         * be removed (in other words, this method will not perform an equal() comparison).
         * @param button    a reference to the button that should be removed.
        public void remove( OutlookBarOperationButton button )
            m_contentPanel.remove( button );
         * Removes all operations that have the specified caption.
         * @param caption   the caption of the operation(s) that should be removed.
        public void removeOperation( String caption )
            Component[] components = m_contentPanel.getComponents();
            for( int i=0; i<components.length; i++ )
                Component component = components;
    if( component != null && component instanceof AbstractButton )
    if( ((AbstractButton)component).getText().equals( caption ) )
    m_contentPanel.remove( i );
    public static void main( String[] args )
    JFrame frame = new JFrame( "OutlookBarCategorButton" );
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.getContentPane().setLayout( new BorderLayout() );
    OutlookBarCategoryPanel obcp = new OutlookBarCategoryPanel();
    obcp.add( new OutlookBarOperationButton( "foo", new ImageIcon( "images/History24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "bar", new ImageIcon( "images/Help24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "foobar", new ImageIcon( "images/Cut24.gif" ) ) );
    obcp.add( new OutlookBarOperationButton( "index 2", new ImageIcon( "images/isl_faninn.png" ) ), 2 );
    frame.getContentPane().add( obcp, BorderLayout.WEST );
    frame.pack();
    frame.show();
    And here is the code for the VerticalFlowLayout class:
    import java.awt.*;
    * A layout manager that works like the default layout manager in swing
    * (FlowLayout) except that it arranges its components vertically instead
    * of horizontally.
    * @version $Revision: 1.1 $ $Date: 2003/03/11 13:37:38 $
    public class VerticalFlowLayout implements LayoutManager
        private int m_vgap;
         * Creates a new instance of the class with an initial vertical gap of 0
         * pixels.
        public VerticalFlowLayout()
            this( 0 );
         * Creates a new instance of the class with an initial vertical gap of
         * the specified number of pixels.
         * @param vgap  the number of pixels to use as a gap between
         *              components
        public VerticalFlowLayout( int vgap )
            m_vgap = vgap;
         * Lays out the container in the specified panel.
         * @param theParent the component which needs to be laid out
        public void layoutContainer( Container theParent )
            Insets insets = theParent.getInsets();
            int w = theParent.getSize().width - insets.left - insets.right;
            int numComponents = theParent.getComponentCount();
            if( numComponents == 0 )
                return;
            int y = insets.top;
            int x = insets.left;
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent(i);
                if( c.isVisible() )
                    Dimension d = c.getPreferredSize();
                    c.setBounds( x, y, w, d.height );
                    y += d.height + m_vgap;
         * Calculates the minimum size dimensions for the specified
         * panel given the components in the specified parent container.
         * @param theParent the component to be laid out
         * @see #preferredLayoutSize
        public Dimension minimumLayoutSize( Container theParent )
            Insets insets = theParent.getInsets();
            int maxWidth = 0;
            int totalHeight = 0;
            int numComponents = theParent.getComponentCount();
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent( i );
                if( c.isVisible() )
                    Dimension cd = c.getMinimumSize();
                    maxWidth = Math.max( maxWidth, cd.width );
                    totalHeight += cd.height;
            Dimension td = new Dimension( maxWidth + insets.left + insets.right,
                    totalHeight + insets.top + insets.bottom + m_vgap * numComponents );
            return td;
         * If the layout manager uses a per-component string,
         * adds the component <code>comp</code> to the layout,
         * associating it
         * with the string specified by <code>name</code>.
         * @param name the string to be associated with the component
         * @param comp the component to be added
        public void addLayoutComponent( String name, Component comp )
         * Removes the specified component from the layout.
         * @param comp the component to be removed
        public void removeLayoutComponent( Component comp )
         * Calculates the preferred size dimensions for the specified
         * panel given the components in the specified parent container.
         * @param theParent the component to be laid out
         * @see #minimumLayoutSize
        public Dimension preferredLayoutSize( Container theParent )
            Insets insets = theParent.getInsets();
            int maxWidth = 0;
            int totalHeight = 0;
            int numComponents = theParent.getComponentCount();
            for( int i = 0; i < numComponents; ++i )
                Component c = theParent.getComponent( i );
                if( c.isVisible() )
                    Dimension cd = c.getPreferredSize();
                    maxWidth = Math.max( maxWidth, cd.width );
                    totalHeight += cd.height;
            Dimension td = new Dimension( maxWidth + insets.left + insets.right,
                    totalHeight + insets.top + insets.bottom + m_vgap * numComponents );
            return td;

    You can use calligraphy/ art brush strokes, can you not? Some of them come with AI and you can find quite a few on ze interweb. You could even create your own, if need be.
    Mylenium

  • Adjust position and size of textField and button...

    Dear All,
    I have the following sample program which has a few textFields and a button, but the positions are not good. How do I make the textField to be at the right of label and not at the bottom of the label ? Also how to adjust the length of textField and button ? The following form design looks ugly. Please advise.
    import javax.swing.*; //This is the final package name.
    //import com.sun.java.swing.*; //Used by JDK 1.2 Beta 4 and all
    //Swing releases before Swing 1.1 Beta 3.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.text.*;
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    public class SwingApplication extends JFrame {
    private static String labelPrefix = "Number of button clicks: ";
    private int numClicks = 0;
    String textFieldStringVEHNO = "Vehicle No";
    String textFieldStringDATEOFLOSS = "Date of Loss";
    String textFieldStringIMAGETYPE = "Image Type";
    String textFieldStringIMAGEDESC = "Image Description";
    String textFieldStringCLAIMTYPE = "Claim Type";
    String textFieldStringSCANDATE = "Scan Date";
    String textFieldStringUSERID = "User ID";
    String ImageID;
    public Component createComponents() {
    //Create text field for vehicle no.
    final JTextField textFieldVEHNO = new JTextField(5);
    textFieldVEHNO.setActionCommand(textFieldStringVEHNO);
    //Create text field for date of loss.
    final JTextField textFieldDATEOFLOSS = new JTextField(10);
    textFieldDATEOFLOSS.setActionCommand(textFieldStringDATEOFLOSS);
    //Create text field for image type.
    final JTextField textFieldIMAGETYPE = new JTextField(10);
    textFieldIMAGETYPE.setActionCommand(textFieldStringIMAGETYPE);
    //Create text field for image description.
    final JTextField textFieldIMAGEDESC = new JTextField(10);
    textFieldIMAGEDESC.setActionCommand(textFieldStringIMAGEDESC);
    //Create text field for claim type.
    final JTextField textFieldCLAIMTYPE = new JTextField(10);
    textFieldCLAIMTYPE.setActionCommand(textFieldStringCLAIMTYPE);
    //Create text field for scan date.
    final JTextField textFieldSCANDATE = new JTextField(10);
    textFieldSCANDATE.setActionCommand(textFieldStringSCANDATE);
    //Create text field for user id.
    final JTextField textFieldUSERID = new JTextField(10);
    textFieldUSERID.setActionCommand(textFieldStringUSERID);
    //Create some labels for vehicle no.
    JLabel textFieldLabelVEHNO = new JLabel(textFieldStringVEHNO + ": ");
    textFieldLabelVEHNO.setLabelFor(textFieldVEHNO);
    //Create some labels for date of loss.
    JLabel textFieldLabelDATEOFLOSS = new JLabel(textFieldStringDATEOFLOSS + ": ");
    textFieldLabelDATEOFLOSS.setLabelFor(textFieldDATEOFLOSS);
    //Create some labels for image type.
    JLabel textFieldLabelIMAGETYPE = new JLabel(textFieldStringIMAGETYPE + ": ");
    textFieldLabelIMAGETYPE.setLabelFor(textFieldIMAGETYPE);
    //Create some labels for image description.
    JLabel textFieldLabelIMAGEDESC = new JLabel(textFieldStringIMAGEDESC + ": ");
    textFieldLabelIMAGEDESC.setLabelFor(textFieldIMAGEDESC);
    //Create some labels for claim type.
    JLabel textFieldLabelCLAIMTYPE = new JLabel(textFieldStringCLAIMTYPE + ": ");
    textFieldLabelCLAIMTYPE.setLabelFor(textFieldCLAIMTYPE);
    //Create some labels for scan date.
    JLabel textFieldLabelSCANDATE = new JLabel(textFieldStringSCANDATE + ": ");
    textFieldLabelSCANDATE.setLabelFor(textFieldSCANDATE);
    //Create some labels for user id.
    JLabel textFieldLabelUSERID = new JLabel(textFieldStringUSERID + ": ");
    textFieldLabelUSERID.setLabelFor(textFieldUSERID);
    Object[][] data = {
    {"Mary", "Campione",
    "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
    "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
    "Chasing toddlers", new Integer(2), new Boolean(false)},
    {"Mark", "Andrews",
    "Speed reading", new Integer(20), new Boolean(true)},
    {"Angela", "Lih",
    "Teaching high school", new Integer(4), new Boolean(false)}
    String[] columnNames = {"First Name",
    "Last Name",
    "Sport",
    "# of Years",
    "Vegetarian"};
    final JTable table = new JTable(data, columnNames);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    final JLabel label = new JLabel(labelPrefix + "0 ");
    JButton buttonOK = new JButton("OK");
    buttonOK.setMnemonic(KeyEvent.VK_I);
    buttonOK.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
              try {
    numClicks++;
              ImageID = textFieldVEHNO.getText() + textFieldDATEOFLOSS.getText() + textFieldIMAGETYPE.getText();
    label.setText(labelPrefix + ImageID);
              ScanSaveMultipage doScan = new ScanSaveMultipage();
              doScan.start(ImageID);
         catch (Exception ev)
    label.setLabelFor(buttonOK);
    * An easy way to put space between a top-level container
    * and its contents is to put the contents in a JPanel
    * that has an "empty" border.
    JPanel pane = new JPanel();
    pane.setBorder(BorderFactory.createEmptyBorder(
    20, //top
    30, //left
    30, //bottom
    20) //right
    pane.setLayout(new GridLayout(0, 1));
         pane.add(textFieldLabelVEHNO);
         pane.add(textFieldVEHNO);
         pane.add(textFieldLabelDATEOFLOSS);
         pane.add(textFieldDATEOFLOSS);
         pane.add(textFieldLabelIMAGETYPE);
         pane.add(textFieldIMAGETYPE);
         pane.add(textFieldLabelIMAGEDESC);
         pane.add(textFieldIMAGEDESC);
         pane.add(textFieldLabelCLAIMTYPE);
         pane.add(textFieldCLAIMTYPE);
         pane.add(textFieldLabelDATEOFLOSS);
         pane.add(textFieldDATEOFLOSS);
         pane.add(textFieldLabelUSERID);
         pane.add(textFieldUSERID);
    pane.add(buttonOK);
         pane.add(table);
    //pane.add(label);
    return pane;
    public static void main(String[] args) {
    try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }
    //Create the top-level container and add contents to it.
    JFrame frame = new JFrame("SwingApplication");
    SwingApplication app = new SwingApplication();
    Component contents = app.createComponents();
    frame.getContentPane().add(contents, BorderLayout.CENTER);
    //Finish setting up the frame, and show it.
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

    Post Author: Ranjit
    CA Forum: Crystal Reports
    Sorry but, i've never seen formula editor for altering position and size. If you know one please navigate me.
    I guess you have updated formula editor beside "Lock size and position" - if yes its not right. There is only one editor beside 4 items and editor is actually for Suppress.
    Anyways, A trick to change size a position is:
    Create 4-5 copies (as many as you expect positions) of the text object. place each at different positions,  right click, Format, Suppress and in formula editor for suppress write the formula: If your condition is true, Suppress=false, else true.
    Position will not change but user will feel; for different conditions -position is changed
    Hope this helps.
    Ranjit

  • Combo box popup width adjusting no longer work in 1.0.6_26-b03

    Previously, I was able to adjusting combo box popup's width, by referring to the technique described in [http://tips4java.wordpress.com/2010/11/28/combo-box-popup/|http://tips4java.wordpress.com/2010/11/28/combo-box-popup/]. During that time, I was using 1.0.6_24-b07.
    However, after I update my Java runtime to 1.0.6_26-b03, things broke.
    Here is the screen shoot.
    [Workable screen shoot|http://i.imgur.com/0elo7.png]
    [Not workable screen shoot|http://i.imgur.com/BeKMy.png]
    Here is the code snippet to demonstrate this problem.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * NewJFrame.java
    * Created on Aug 9, 2011, 4:13:41 AM
    package experiment;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JComboBox;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    import javax.swing.event.PopupMenuEvent;
    import javax.swing.event.PopupMenuListener;
    import javax.swing.plaf.basic.BasicComboPopup;
    * @author yccheok
    public class NewJFrame extends javax.swing.JFrame {
         * Adjust popup for combo box, so that horizontal scrollbar will not display.
         * Resize JComboBox dropdown doesn't work without customized ListCellRenderer
         * http://www.camick.com/java/source/BoundsPopupMenuListener.java
         * @param comboBox The combo box
        public static void adjustPopupWidth(JComboBox comboBox) {
            if (comboBox.getItemCount() == 0) return;
            Object comp = comboBox.getAccessibleContext().getAccessibleChild(0);
            if (!(comp instanceof BasicComboPopup)) {
                return;
            BasicComboPopup popup = (BasicComboPopup)comp;
            JList list = popup.getList();
            JScrollPane scrollPane = getScrollPane(popup);
            // Just to be paranoid enough.
            if (list == null || scrollPane == null) {
                return;
            //  Determine the maximimum width to use:
            //  a) determine the popup preferred width
            //  b) ensure width is not less than the scroll pane width
            int popupWidth = list.getPreferredSize().width
                            + 5  // make sure horizontal scrollbar doesn't appear
                            + getScrollBarWidth(popup, scrollPane);
            Dimension scrollPaneSize = scrollPane.getPreferredSize();
            popupWidth = Math.max(popupWidth, scrollPaneSize.width);
            //  Adjust the width
            scrollPaneSize.width = popupWidth;
            scrollPane.setPreferredSize(scrollPaneSize);
            scrollPane.setMaximumSize(scrollPaneSize);
         *  I can't find any property on the scrollBar to determine if it will be
         *  displayed or not so use brute force to determine this.
        private static int getScrollBarWidth(BasicComboPopup popup, JScrollPane scrollPane) {
            int scrollBarWidth = 0;
            Component component = popup.getInvoker();
            if (component instanceof JComboBox) {
                JComboBox comboBox = (JComboBox)component;
                if (comboBox.getItemCount() > comboBox.getMaximumRowCount()) {
                    JScrollBar vertical = scrollPane.getVerticalScrollBar();
                    scrollBarWidth = vertical.getPreferredSize().width;
            return scrollBarWidth;
         *  Get the scroll pane used by the popup so its bounds can be adjusted
        private static JScrollPane getScrollPane(BasicComboPopup popup) {
            JList list = popup.getList();
            Container c = SwingUtilities.getAncestorOfClass(JScrollPane.class, list);
            return (JScrollPane)c;
        /** Creates new form NewJFrame */
        public NewJFrame() {
            initComponents();
            this.jComboBox1.addPopupMenuListener(getPopupMenuListener());
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jComboBox1 = new javax.swing.JComboBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "This is a very long text. This is a very long text" }));
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(82, 82, 82)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(242, Short.MAX_VALUE))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(34, 34, 34)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(246, Short.MAX_VALUE))
            pack();
        }// </editor-fold>
        * @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 PopupMenuListener getPopupMenuListener() {
            return new PopupMenuListener() {
                @Override
                public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                    // We will have a much wider drop down list.
                    adjustPopupWidth(jComboBox1);
                @Override
                public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
                @Override
                public void popupMenuCanceled(PopupMenuEvent e) {
        // Variables declaration - do not modify
        private javax.swing.JComboBox jComboBox1;
        // End of variables declaration
    }

    I had came across another workaround as stated here.
    [http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough|http://www.jroller.com/santhosh/entry/make_jcombobox_popup_wide_enough]
    The popup's is having enough width to show all items. However, it is not perfect still, as the width is little too much. I still can see some extra space at the tailing of the list.
    The workaround is as follow.
    import javax.swing.*;
    import java.awt.*;
    import java.util.Vector;
    // got this workaround from the following bug:
    //      http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4618607
    public class WideComboBox extends JComboBox{
        public WideComboBox() {
        public WideComboBox(final Object items[]){
            super(items);
        public WideComboBox(Vector items) {
            super(items);
        public WideComboBox(ComboBoxModel aModel) {
            super(aModel);
        private boolean layingOut = false;
        public void doLayout(){
            try{
                layingOut = true;
                super.doLayout();
            }finally{
                layingOut = false;
        public Dimension getSize(){
            Dimension dim = super.getSize();
            if(!layingOut)
                dim.width = Math.max(dim.width, getPreferredSize().width);
            return dim;
    }

  • JScrollPane not working? Please help

    Hi there,
    I am trying to incorporate a JScrollPane into a JList in my program, basically I make it so that JList is comprised of array of Strings. So the code looks like:
    javax.swing.JPanel          jpanelListSnps            = new javax.swing.JPanel();
    jpanelListSnps.setLayout(new java.awt.BorderLayout());
    String[] stringArray    =  new String[123] //that's the actual amount of elements in the string
    //initializing each elements of array....I will skip that part
    javax.swing.JScrollPane  jscroll  =  new javax.swing.JScrollPane(stringArray);
    jscroll.setPreferredSize(new java.awt.Dimension(30,30));
    jlistSnps.addListSelectionListener(this);
    jpanelListSnps.add(jlistSnps,"West");
    jpanelListSnps.add(jscroll  ,"East");
    jscroll.setAlignmentX(jpanelListSnps.RIGHT_ALIGNMENT);And I see the scrollbar, but I don't think the size is not properly adjusted. Also, I don't see the tab for the scrollbar. I don't know what is wrong with this code. Any suggestions or ideas would be much appreciated. Thank you in advance.
    Regards,
    Young

    JList list = new JList( stringArray );
    JScrollPane scrollPane = new JScrollPane( list );
    panel.add(scrollPane, BorderLayout.EAST);

  • Help with JScrollPane

    I have a JScrollPane that I need to add multiple components to. That includes 5 JButtons, and 5 Jtree's.
    I need to add all of the components at once, making the JTree's visible and invisible by clicking the JButton's. My first problem is when I try to add multiple objects to the JScrollPane using the default layout manager. The last object added is always stretched to fill the entire viewport. This makes the objects first added un-viewable. So I decided to first add all of the objects to a Box then add the Box to the scrollpane.
    My second problem occurs when I make a JTree visible, aftering adding it to the Box. It draws the tree completely from top to bottom as it should, but clips the right end of titles on the nodes. The horizontal scroll adjusts enought so that you can scroll far enough to the right, but the titles are cut off.
    If I add one of the JTree's directly to the JScrollPane it behaves as it should, showing the complete node titles.
    I've tried revalidating, updating, and repainting without success.
    So, first question is can multiple objects be added to a JScrollPane using the default layout manager, without having the last object hide the previously added objects?
    Secondly, does anyone know why nodes in a JTree would be clipped when added to a Box then added the Box added to a JScrollPane. And more importantly how to fix it.
    Any help would be appreciated,
    Thanks,
    Jim

    Hi there
    Im not sure on exactly what you are trying to do.
    But if you want multiple components in one JScrollPane
    I would use a JPanel that I would add to the JScrollPane
    On that JPanel I would then add my components.
    I would also use GridBagLayout instead of any other layout manager. Thats because it is the most complex
    layout manager and it will arrange the components as I whant.
    If you whant to be able to remove a component from the view by making them invisible. I think I would consider
    JLayeredPane.
    on a JLayeredPane you add components on different layers. Each component is positionend exactly with setLocation or setBounds. This is the most exact thing to use. The JLayeredPane uses exact positioning of its components. which can be usefull when you use
    several components that will be visible at different times
    /Markus

  • Stop scroll bar in JScrollPane from updating viewport when dragging knob

    Hi,
    Does anyone know if it's possible to stop the JScrollPane from updating the viewport whilst dragging the knob of the scrollbar and only update once released.
    The problem I have is that the view of the scroll panes viewport is a JList that has an underlying model of a RandomAccessFile which can be very large. So when the user is dragging the scrollbars it will be accessing the file system to retrieve the relevant data for the JList.
    I've tried creating my own JScrollBar and adding a AdjustmentListener to ignore events whilst dragging:
    class MyAdjustmentListener implements AdjustmentListener {
    // This method is called whenever the value of a scrollbar is changed,
    // either by the user or programmatically.
    public void adjustmentValueChanged(AdjustmentEvent evt) {
    Adjustable source = evt.getAdjustable();
    // getValueIsAdjusting() returns true if the user is currently
    // dragging the scrollbar's knob and has not picked a final value
    if (evt.getValueIsAdjusting()) {
    // The user is dragging the knob
    return;
    Looking through the JScrollBar code it has a model that will fire adjustment events anyway, which I suppose are being picked up by the JScrollPane somewhere.
    I could use my own JScrollBar and not add it to the scroll pane and process the adjustment events myself and update the JList but I was wondering if there is a better way.
    Many Thanks,
    Martin.

    Two small changes seem to do the trick. You may want to test it thoroughly though ;)import javax.swing.BoundedRangeModel;
    import javax.swing.DefaultBoundedRangeModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class OneStepScroller {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new OneStepScroller().makeUI();
       public void makeUI() {
          Object[] data = new Object[200];
          for (int i = 0; i < data.length; i++) {
             data[i] = "Item Number " + i;
          JList list = new JList(data);
          JScrollPane scrollPane = new JScrollPane(list);
          BoundedRangeModel model = scrollPane.getVerticalScrollBar().getModel();
          final JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
          scrollBar.setModel(new DefaultBoundedRangeModel(model.getValue(),
                model.getExtent(), model.getMinimum(), model.getMaximum()) {
             int oldValue;
             @Override
             public int getValue() {
                // changed here
                if (!getValueIsAdjusting() && !(oldValue == super.getValue())) {
                   oldValue = super.getValue();
                   // added this
                   fireStateChanged();
                return oldValue;
          JFrame frame = new JFrame("");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 400);
          frame.setLocationRelativeTo(null);
          frame.add(scrollPane);
          frame.setVisible(true);
    }db

  • Mouse Coordinate issues caused by Scaling Components in a JScrollPane

    Hi All,
    I've been attempting to write a program that includes a simple modeler. However, I've been having some trouble with being able to select components when attempting to implement zoom functionality - when I "zoom" (which is done via scroll wheel) using the scale Graphics2D method, while it zooms correctly, the mouse location of components do not seem scale.
    I've tried one of the solutions found on the forums here (create a custom event queue that adjusts the mouse coordinates) and while it seemed to work initially, if I zoom in and adjust the current view position using the scrollbars, certain components contained in the JPane will become un-selectable and I haven't been able to work out why.
    I've attached a SSCCE that reproduces the problem below - it implements a JScrollPane with a JPane with a few selectable shapes set as the Viewport. The zoom is done using the mouse scroll wheel (with wheel up being zoom in and wheel down being zoom out)
    Any help in order to fix the selection/de-selection issues on zoom would be greatly appreciated! I've spent some time reading through the forums here but have unfortunately not been able to find a workable solution around it.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Tester extends JScrollPane
        public Tester() {
            this.setViewportView(new Model());
        public static void main (String[] args) {
            JFrame main = new JFrame();
            main.add(new Tester());
            main.setSize(500,300);
            main.setResizable(false);
            main.setVisible(true);
    class Model extends JPanel implements MouseListener, MouseWheelListener
        private GfxClass selection = null;
        private static double zoomLevel = 1;
        // zoom methods
        public void setZoom(double zoom) {
            if( zoom < 0 && zoomLevel > 1.0)
                zoomLevel += zoom;
            if( zoom > 0 && zoomLevel < 5.0)
                zoomLevel += zoom;
        public static double getZoom() { return zoomLevel; }
        public void resetZoom() { zoomLevel = 1; }
        public Model() {
            super(null);
            addMouseListener(this);
            addMouseWheelListener(this);
            MyEventQueue meq = new MyEventQueue();
            Toolkit.getDefaultToolkit().getSystemEventQueue().push(meq);
            for(int i = 0; i <7; i++) {
                double angle = Math.toRadians(i * 360 / 7);
                GfxClass oc_tmp = new GfxClass((int)(200 + 150 * Math.cos(angle)), (int)(125 + 100 * Math.sin(angle)), "Element"+i);
                add(oc_tmp);
            repaint();
        public void paint (Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            AffineTransform oldTr=g2.getTransform();
            g2.scale(getZoom(),getZoom());
            super.paint(g2);
            g2.setTransform(oldTr);
            setBackground (Color.white);
            super.paintBorder(g2);
        private static class MyEventQueue extends EventQueue  {
            protected void dispatchEvent(AWTEvent event) {
                AWTEvent event2=event;
                if ( !(event instanceof MouseWheelEvent) && (event instanceof MouseEvent) ) {
                    if ( event.getSource() instanceof Component && event instanceof MouseEvent) {
                        MouseEvent me=(MouseEvent)event2;
                        Component c=(Component)event.getSource();
                        Component cursorComponent=SwingUtilities.getDeepestComponentAt(c, me.getX(), me.getY());
                        JPanel zContainer= getZoomedPanel(cursorComponent);
                        if (zContainer!=null) {
                            int x=me.getX();
                            Point p=SwingUtilities.convertPoint(zContainer,0,0,(Component)event.getSource());
                            int cX=me.getX()-p.x;
                            x=x-cX+(int)(cX/getZoom());
                            int y=me.getY();
                            int cY=me.getY()-p.y;
                            y=y-cY+(int)(cY/getZoom());
                            MouseEvent ze = new MouseEvent(me.getComponent(), me.getID(), me.getWhen(), me.getModifiers(), x, y, me.getClickCount(), me.isPopupTrigger());
                            event2=ze;
                super.dispatchEvent(event2);
        public static JPanel getZoomedPanel(Component c) {
            if (c == null)
                return null;
            else if (c instanceof Model)
                return (Model)c;
            else
                return getZoomedPanel(c.getParent());
        private void deselectAll() {
            if(selection != null)
                selection.setSelected(false);
            selection = null;
        public void mouseClicked(MouseEvent arg0)  {    }
        public void mouseEntered(MouseEvent arg0)  {    }
        public void mouseExited(MouseEvent arg0)   {    }
        public void mouseReleased(MouseEvent arg0) {    }   
        public void mousePressed(MouseEvent me) {
            Component c1 = findComponentAt(me.getX(),me.getY());
            if(c1 instanceof GfxClass)
                if(selection != null)
                    selection.setSelected(false);
                selection = (GfxClass)c1;
                selection.setSelected(true);
            else
                deselectAll();
            repaint();
            return;
        public void mouseWheelMoved(MouseWheelEvent e) { // controls zoom
                int notches = e.getWheelRotation();
                if (notches < 0)
                    setZoom(0.1);
                else
                    setZoom(-0.1);
                this.setSize(new Dimension((int)(500*getZoom()),(int)(300*getZoom())));           
                this.setPreferredSize(new Dimension((int)(500*getZoom()),(int)(300*getZoom())));     
                repaint();
    class GfxClass extends Component { // simple graphical component
        private boolean isSelected = false;
        private String name;
        public GfxClass(int xPos, int yPos, String name) {
            this.name = name;
            this.setLocation(xPos,yPos);
            this.setSize(100,35);
        public void setSelected(boolean b) {
            if( b == isSelected )
                return;
            isSelected = b;
            repaint();
        public boolean isSelected() {
            return isSelected;
        public void paint(Graphics g2) {
            Graphics2D g = (Graphics2D)g2;
            if( isSelected )
                g.setColor(Color.RED);
            else
                g.setColor(Color.BLUE);
            g.fill(new Ellipse2D.Double(0,0,100,35));
            g.setColor(Color.BLACK);
            g.drawString(name, getSize().width/2 - 25, getSize().height/2);
    }Edited by: Kys99 on Feb 22, 2010 9:09 AM
    Edited by: Kys99 on Feb 22, 2010 9:10 AM

    Delete your EventQueue class. Change one line of code in your mouse pressed method.
    public void mousePressed(MouseEvent me) {
        Component c1 = findComponentAt((int) (me.getX()/getZoom()),
                                       (int) (me.getY()/getZoom()));
    }

  • Automatic adjusting of the volum level

    Does anybody know in witch way/how the player does the automatic adjusting of the volum level? How does the automatic adjusting of the volum level work? Is it just the decibel that is "normalising"? How does the player measure it? Are the frequenses exactly the same in a song/tune after the automatic adjusting?
    Is there anything else in the sound that is influenced in any way?
    JN
    Macbook Pro   Mac OS X (10.4.8)  

    Again, camickr is great, and, clever.
    Here's the working code basing on his suggestion.
    It is my first time for calling prepareRenderer() from within application code.
    I have had overridden it many times in the past, though.
        width = 0;
        cc = table.getColumnCount();
        rc = table.getRowCount();
        for (int c = 0; c < cc; ++c){
          maxcw = 0;
          for (int r = 0; r < rc; ++r){
            Component compo
             = table.prepareRenderer(table.getCellRenderer(r, c), r, c);
            int w = compo.getPreferredSize().width;
            if (w > maxcw){
              maxcw = w;
          maxcw += 7; // somehow, this handcraft is necessary
          table.getColumn(table.getColumnName(c)).setPreferredWidth(maxcw);
          width += maxcw;
        height = (table.getRowCount() + 1) * table.getRowHeight(); // +1 == header
        js.setPreferredSize(new Dimension(width, height));
        // js is a JScrollPane enclosing the table

  • Implementing a graph scrolling using JScrollPane component

    I would like to ask a question apropos using of JScrollPane component. A part of the default behaviour of this component is adjusting the component's state when the size of the client changes. But, I need to achieve an opposite effect - I need to adjust a size of my client when the size of JScrollPane (and its viewport) changes (for instance, when the user resizes the frame).
    I implement a graph component which will show the graph of a time function. This component should always show nnn seconds without connection to the size of the scroll pane's viewport. So, if the the scroll pane component is resized I need to adjust the size of my client in order to keep the displayed time period unchanged.
    Now the question: how may I check the size of the viewport when the size of the JScrollPane changes? And whether I can do it even if the JScrollPane component has no client?
    If you know any other method of achieving the same effect, plese let me know.
    Thanks.

    I still find getExten\tSize (and getViewRect) work for me. Here's another demo.
    In my component, there's a big oval thats bounded by my component and a smaller
    oval that should track with the viewport's bounds.
    import java.awt.*;
    import javax.swing.*;
    public class ViewportLemonJuice extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawOval(0, 0, getWidth(), getHeight());
            Container parent = (Container) getParent();
            if (parent instanceof JViewport) {
                Rectangle rect = ((JViewport) parent).getViewRect();
                g.drawOval(rect.x, rect.y, rect.width, rect.height);
        public static void main(String[] args) {
            JComponent comp = new ViewportLemonJuice();
            comp.setPreferredSize(new Dimension(800,800));
            JScrollPane sp = new JScrollPane(comp);
            sp.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            JFrame f = new JFrame("ViewportLemonJuice");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(sp);
            f.setSize(500,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • Update JScrollBar Extent when JScrollPane Component Changes Preferred Size

    Hi folks,
    I have an interesting, but concise problem that I've been working on for a few days but haven't had any luck.
    In Java 1.5 or Java6, I have a JScrollPane which contains a JPanel. The settings of the scrollbar (for example, the Extent [the width of the "thumb" or "slider" on the scrollbar]) are determined based on the dimension of the underlying contained component, in particular, the Preferred Size.
    My problem is this. The underlying component has a "zoom" capability, such that the actual size of the component can and does change (i.e., zooming out reduces its preferred size).
    Happily, the consequence of this design is that the "size" or extent of the scrollbar sliders/thumbs adjusts to give visual indication of the proportion of the current view (ViewPort View dimension) to the underlying component's dimension.
    The problem is, the scrollbar sliders do NOT automatically update their size in response to programatically changing the JScrollPane's contained component's PreferredSize. They WILL be updated if I RESIZE the parent JFrame manually.
    But for the life of me, I can't get those sliders to update programatically. I've tried repaint(), update, validate(), etc. on the JScrollPane but no luck.
    I've done a debug to get into the stack trace of the Sun code during run time, and there's a lot going on... there's a doLayout(), a reshape() (deprecated), firing various property changes, but I just can't seem to find a good hook into getting the scrollbar to update its internal Bounds model and repaint accordingly. Calling setBounds() on the JScrollPane I think would trigger it, however, looking at the code.. it seems to ignore firing property events and repainting of the bounds themselves didn't actually change (i.e. no action happens if the current dimension and specified dimension in the argument to setBounds() are the same).
    Any ideas here on how to this to get those sliders to update programatically with a new value for the extent?
    Thanks,
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Understood! It was my intention to give credit and now I'm happy to do so! I've now assigned the Duke Points. Minor usability issue, it was not obvious how to do this the first time (and I did poke around a little before I gave up earlier in the day, reverting to just assigning him the correct question). I've got it now though! Thanks again--definitely knocked out an issue I was having today and allowed me to move on to add'l development work today.
    All the best!
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to make JScrollPane scroll faster?

    Hi,
    I have tried to develop on a program to zoom in or zoom out the image�a graph which is plotted using the method draw from Graphics2D. In the program, I am given about 1000 points, which are supposed to be plotted one by one suing the draw method, which later form a graph.
    I have put the JPanel, where the output of the graph is displayed, into a JscrollPane to enable scrolling of large image. However, when I am trying to scroll the image, it happen to me that the scrolling is extremely slow. When I click at the scrolling bar to scroll down the image, it take some time before the image is scrolled down.
    My doubt will be is there any method to make the scrolling on the JscrollPane to become faster?does this involve double buffering?
    Thank you.

    This may not be the answer to your problem, but I thought I would throw it out there. One reason it might scroll slowly is because by default the JScrollPane only moves 1 pixel for every click of the scroll bar. You can adjust this by having your JPanel implement the Scrollable interface.
    Here is a code sample -
    // implement Scrollable interface
    public Dimension getPreferredScrollableViewportSize()
    return getPreferredSize();
    public int getScrollableBlockIncrement( Rectangle r, int orientation, int direction )
    return 10;
    public boolean getScrollableTracksViewportHeight()
    return false;
    public boolean getScrollableTracksViewportWidth()
    return false;
    public int getScrollableUnitIncrement( Rectangle r, int orientation, int direction )
    return 10;
    Whatever number you have your getScrollableUnitIncrement and getScrollableBlockIncrement methods return is how many pixels your component will scroll for each click of the scroll bar.
    Give this a try.

Maybe you are looking for

  • Writing Picture files to iPod

    When I try to add pictures to the iPod I get the message: iPod may not be synchronized. Disk is locked. I have turned use of disk on. No problem to synchronize music.

  • Selected music not playing in slideshow

    I have four tracks from my iTunes folder I want to play in a slideshow. I have followed directions but only the first song plays and it plays over and over, ignoring the other 3 songs. Anyone else have this problem.

  • Where do I authorize my computer for Windows

    I have been searching for ways to authorize my computer for this new Itune. It saids: Store> Authorize computer. Where is it? I can't find it. Driving me crazy. Please help.

  • IPhoto is suddenly not responding

    Hi, I'm using OS X version 10.7.5 and iPhoto. It will open and show the most recent upload, but it just keeps loading and loading. I've shut down and restarted several times, with no success.

  • OS X 10.5.4 Keeps Freezing my computer!  First time experienced

    The main screen has a grey drop down that says that I need to restart my computer by holding down the power button, it boots up fine, but it keeps freezing every few hours. Here are the programs that I typically run at the same time: VLC Azerus Camin