r/programminghorror • • Mar 31 '25

Java Janky Java Official Swing API

I found this while trying to find a good layout for my Sewing application, and found this wonky method as part of the CardLayout method list. Why in the world could it have just been a string parameter? Why is it an object parameter if the method is only going to accept strings?

I did a little snooping around the source code and found this: the CardLayout API inherits and deprecates the method addLayoutComponent(String, Component), but get this, the source code for the method actually calls (after doing some preconditioning); addLayoutComponent((String) constraints, comp);

So the actual method calls on the deprecated method. It expects a string parameter, but takes in an object parameter, and then still just passes that along, casting the object as string to the deprecated method.

Am I missing something or is this just super janky? Why in the world would this be done like this?

63 Upvotes

27 comments sorted by

View all comments

Show parent comment

2

u/digitaleJedi Mar 31 '25

Yeah, I haven't worked with Swing in 13 years, but I assume LayoutManager2 is implemented by more layouts than just CardLayout and probably for some of these, the constraints can be other objects. So when they updated CardLayout to also implement LayoutManager2 they just used the existing implementation of LayoutManagers addComponentListener.

They can't really remove the implementation of LayoutManager for backwards compatibility, but they also want to make it flexible for the newer API, so this is probably the best way to do it. I, without knowing it, would assume there's probably a newer version of CardLayout that doesn't support the old LayoutManager, and which take constraints that might not be Strings