Search code examples
javaswingnetbeansjscrollpanejscrollbar

How to scroll down a vertical scroll bar on a JScrollPane?


I use Netbeans with Java/Swing and I have a problem with my scroll pane. First of all I have two JPanel components inside my scroll panel. When I init all components I make not visible the second panel. I wanted that when I click on a button, the second panel set visible (it works) and the vertical scroll bar moves to down to show the second panel.

I use this code when I click on button:

public void eventoAdd() {
      miVista.getJpanelSegundo().setVisible(true);
      miVista.getJScrollPane1().getVerticalScrollBar().setValue(280);
 }

The vertical scroll bar never goes to the bottom at first click, but at second attempt seem like the vertical scroll bar goes to the bottom. What is the problem?

PS: I see a lot of questions, but there aren't answers about this specific question.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author rober
 */
public class View extends javax.swing.JFrame {

    /**
     * Creates new form View
     */
    public View() {
    initComponents();
    jPanelSecond.setVisible(false);

    }

    /**
     * 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() {

    jScrollPaneFirst = new javax.swing.JScrollPane();
    jPanelMain = new javax.swing.JPanel();
    jPanelFirst = new javax.swing.JPanel();
    jPanelSecond = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jScrollPaneFirst.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

    jPanelFirst.setBorder(javax.swing.BorderFactory.createTitledBorder("First"));

    javax.swing.GroupLayout jPanelFirstLayout = new javax.swing.GroupLayout(jPanelFirst);
    jPanelFirst.setLayout(jPanelFirstLayout);
    jPanelFirstLayout.setHorizontalGroup(
        jPanelFirstLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 0, Short.MAX_VALUE)
    );
    jPanelFirstLayout.setVerticalGroup(
        jPanelFirstLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 61, Short.MAX_VALUE)
    );

    jPanelSecond.setBorder(javax.swing.BorderFactory.createTitledBorder("Second"));

    javax.swing.GroupLayout jPanelSecondLayout = new javax.swing.GroupLayout(jPanelSecond);
    jPanelSecond.setLayout(jPanelSecondLayout);
    jPanelSecondLayout.setHorizontalGroup(
        jPanelSecondLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 294, Short.MAX_VALUE)
    );
    jPanelSecondLayout.setVerticalGroup(
        jPanelSecondLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 63, Short.MAX_VALUE)
    );

    javax.swing.GroupLayout jPanelMainLayout = new javax.swing.GroupLayout(jPanelMain);
    jPanelMain.setLayout(jPanelMainLayout);
    jPanelMainLayout.setHorizontalGroup(
        jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanelFirst, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jPanelSecond, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    jPanelMainLayout.setVerticalGroup(
        jPanelMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanelMainLayout.createSequentialGroup()
            .addComponent(jPanelFirst, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanelSecond, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap())
    );

    jScrollPaneFirst.setViewportView(jPanelMain);

    jButton1.setText("Add");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPaneFirst, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addGap(98, 98, 98)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPaneFirst, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jButton1))
    );

    pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jPanelSecond.setVisible(true);
    jScrollPaneFirst.getVerticalScrollBar().setValue(280);
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(View.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new View().setVisible(true);
        }
    });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanelFirst;
    private javax.swing.JPanel jPanelMain;
    private javax.swing.JPanel jPanelSecond;
    private javax.swing.JScrollPane jScrollPaneFirst;
    // End of variables declaration                   
}

Solution

  • As a personal preference, I find scrollRectToVisible to be among the most reliable means to achieve this, but you do need to know how to use it

    Scroll

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        jPanelSecond.setVisible(true);
        Rectangle viewBounds = jScrollPaneFirst.getViewportBorderBounds();
        Dimension size = jPanelMain.getPreferredSize();
        jPanelMain.scrollRectToVisible(new Rectangle(0, size.height, viewBounds.width, viewBounds.height));
        //jScrollPaneFirst.getVerticalScrollBar().setValue(280);
    }