Search code examples
javaswingjscrollpanejcheckboxnull-layout-manager

Managing dynamically added JCheckBoxes to JScrollPane


I am working on the functionality of adding JCheckBox to Panel and then adding that Panel to JScrollPane. So far i am done with adding different JCheckBox dynamically to Panel but when i add that same Panel to JScrollPane, it does not shows the JCheckBoxes to JScrollPane

Q.1 What might be the possible reason for same thing not appearing in JScrollPane?

Q.2 Even if i added JCheckBox to Panel and then adding that Panel to JScrollPane how do i manage there setSelected functionality i mean how i can add the ActionListener to that dynamically added JCheckBox?

Note: I am using a AbsoluteLayout for Panel


Solution

  • Use for example GridLayout (1 column and multiple rows).

    Keep array (or list) of the checkboxes. Go through the list adding ActionListener or you can get the main panel's children components, iterate through them casting to JCheckBox and add the listener.

    The worst way is to define preferred size for the panel with AbsoluteLayout.