Search code examples
javaswingjcomponent

Creating a method to handle all Types of Swing Components


In order to save some time when setting the size of Swing Components (JPanel, JLabel, etc.), I am trying to write a method that when called, will set that component's size using 3 of the standard size-defining functions.

I would like to be able to do this:

import CustomComponents;
...
 JPanel xPanel = new JPanel();
 CSize.setDefiniteSize(xPanel, 400, 300);
...

Or (and preferably)

...
 JPanel xPanel = new JPanel();
 xPanel.CSize.setDefiniteSize(400, 300);
...

Here's the code I have so far. The problem is, I want the method to be functional for all types of Swing components, and it seems to only work for the one I specify in the heading.

package CustomComponents;
import javax.swing.JComponent;
import java.awt.Dimension;

public class CSize
{
public static void setDefiniteSize(JComponent c, int h, int w)
{
    Dimension k = new Dimension (h, w);
    c.setMaximumSize(k);
    c.setMinimumSize(k);
    c.setPreferredSize(k);
}
}

As you can see, here I tried using JComponent, but it won't work, as whatever I use it with - say a JPanel - is a JPanel, not a JComponent (even though it's a subclass? I still don't get how this works)


Solution

  • You have to use java.awt.Container, because JFrame is not a direct subclass of JComponent!

    So it should work with the following code:

    package CustomComponents;
    
    import java.awt.Container;
    import java.awt.Dimension;
    
    public class CSize {
        public static void setDefiniteSize(Container c, int h, int w) {
            Dimension k = new Dimension (h, w);
            c.setMaximumSize(k);
            c.setMinimumSize(k);
            c.setPreferredSize(k);
        }
    }
    

    Look at the hierarchy of the components:

    java.awt.Component
      |--java.awt.Container
           |--java.awt.Window
           |    |--java.awt.Frame
           |         |--javax.swing.JFrame
           |--javax.swing.JComponent
                |--javax.swing.JLabel
    

    Even better would be using java.awt.Component, since this class is defining all methods you want to use (setMinimumSize, setMaximumSize and setPreferredSize).