Search code examples
javaswinglayout-managerillegalargumentexceptionboxlayout

BoxLayout not working?


I have this code that seems to throw a IllegalComponentException, and I’m not sure why. It boils down to these lines of code:

JRadioButton setRed = new JRadioButton(“Red", true);
JRadioButton setBlue = new JRadioButton("Blue", false);
JRadioButton setYellow = new JRadioButton("Yellow", false);
JPanel options = new JPanel();
options.add(setBlue, BoxLayout.Y_AXIS);//error here
options.add(setRed, BoxLayout.Y_AXIS);//and probably here too
options.add(setYellow, BoxLayout.Y_AXIS);//and here

Here is the error:

Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
    at java.awt.Container.addImpl(Container.java:1034)
    at java.awt.Container.add(Container.java:406)
    at DrawCanvas.go(DrawCanvas.java:42)
    at DrawCanvas.main(DrawCanvas.java:27)

Solution

  • Your code makes no sense. You don't use the BoxLayout constants when adding components to a JPanel, but rather you use the constants when creating your BoxLayout object, something that you've not yet done.

    You need to:

    • Create a BoxLayout object using an appropriate BoxLayout constant, and passing in a reference to the container that will use this layout.
    • Set your JPanel's layout to this object
    • Add your components to the JPanel without constants.
    • Most importantly, you need to read the tutorial as it's obvious that you're trying to use this tool without first checking this important resource first. You can't guess at this stuff and expect it to work.

    Google: Java BoxLayout tutorial. First hit.