Conversely, this variation of your example overrides the scrollpane's getPreferredSize()
method to provide an arbitrary size. The checkbox uses an ItemListener
to toggle visibility. Note the use of pack()
, which "Causes this Window
to be sized to fit the preferred size and layouts of its subcomponents."
Addendum: This update makes the scroll pane initially invisible and sizes the frame to accommodate.
public class VisibilityDelayExample extends JFrame {
private JCheckBox chckbxAdvancedView;
private JScrollPane scrollPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
VisibilityDelayExample frame = new VisibilityDelayExample();
frame.setVisible(true);
}
});
}
public VisibilityDelayExample() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout(0, 0));
chckbxAdvancedView = new JCheckBox("Advanced View");
chckbxAdvancedView.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e);
scrollPane.setVisible(chckbxAdvancedView.isSelected());
}
});
add(chckbxAdvancedView, BorderLayout.NORTH);
JPanel panel = new JPanel(new GridLayout(0, 1));
for (int j = 0; j < 100; j++) {
panel.add(new JLabel("Label " + j));
}
scrollPane = new JScrollPane(panel) {
@Override
public Dimension getPreferredSize() {
return new Dimension(450, 300);
}
};
add(scrollPane, BorderLayout.CENTER);
pack();
scrollPane.setVisible(false);
setSize(scrollPane.getPreferredSize());
}
}