Question

I have a JScrollPane (with both scrollbars optional (should not cause the problem) Inside of the ScrollPane is a panel with BoxLayout and X_Axis - align. (it contains arbitrary number of Panels with fixed (prefference)Size. The Problem is that the ScrollPane will be much wider than necessary (Horizontal Scrollbar scrolls through "grey screen"). With Y_Axis align it works as it should. Relevant code:

final JPanel forSpecific = new JPanel();

    final JScrollPane scrollSpecific = new JScrollPane(forSpecific,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        forSpecific.setLayout(new BoxLayout(forSpecific,BoxLayout.X_AXIS));

I have no idea whats the poblem and did not find any solution...

EDITED: sry it took some time. The original code was to complex to extract some sscce.. i wrote a test-class. This example works coorect.. but i dont know whats different.. package getdata;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;


public class Sscce {

public static void gui(){
    final JFrame rootframe = new JFrame("Time Series Mining");
    final JPanel mainPanel = new JPanel(new BorderLayout());
    rootframe.setSize(new Dimension(400,400));
    rootframe.setContentPane(mainPanel);
    mainPanel.setLayout(new BorderLayout());
    JPanel center=new JPanel(new GridLayout(2,1));
    JPanel forSpecific=new JPanel();
    forSpecific.setLayout(new BoxLayout(forSpecific, BoxLayout.X_AXIS));
    JPanel test1 = new JPanel();
    test1.setPreferredSize(new Dimension(1000,1000));
    forSpecific.add(test1);
    test1.setBackground(Color.white);
    final JScrollPane scrollSpecific = new JScrollPane(forSpecific);
    center.add(scrollSpecific);
    rootframe.add(center, BorderLayout.CENTER);
    rootframe.setVisible(true);
}
}
Was it helpful?

Solution

//final JScrollPane scrollSpecific = new JScrollPane(forSpecific,
//    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
//    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
final JScrollPane scrollSpecific = new JScrollPane(forSpecific);

Not the problem but the "scrollbar as needed" is the default. You don't need to specify this.

Inside of the ScrollPane is a panel with BoxLayout and X_Axis - align. (it contains arbitrary number of Panels with fixed (prefference)Size.

What is a fixed size?

  • the "main" panel added to the scrollpane
  • the "child" panels added to the main panel

In any case the size should not be fixed, the layout manager should determine the preferred size. Or if you are creating a custom component then you should override the getPreferredSize() method to return the proper size so the layout manager can do its job.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top