Thursday 9 November 2017

java - JFrame cannot find 'pack' method

itemprop="text">

I'm taking a beginning Java class and
an assignment requires that I write a class to represent a JPanel with buttons to
increment and decrement a value and a label to display the value. Then, I have to create
a separate class which instantiates the panel and adds it to a frame. I'm trying to have
the frame resize to fit the size of the panel by running the pack method. I try to call
the frame's pack method by using:




SwingUtilities.getAncestorOfClass(JFrame.class,
this).pack()


I get a
"cannot find symbol - method pack()" error. The getAncestorOfClass is definitely
returning a JFrame, and it is the correct JFrame. When I run the pack method from inside
the driver class where the JFrame is created, there are no problems. Any ideas why it
can't find the pack method? Is it because I'm trying to run this from a separate class
file? I also can't access some other JFrame methods such as getContentPane, but I
am able to access some others such as add.
Huh?



Answer




The method
SwingUtilities.getAncestorOfClass returns a
Container. Now, you know that
Container is really gonna be a JFrame, but the compiler
doesn't. And Java is a static language, not a dynamic one that'll just try to call the
method regardless of whether the class declares it or
not.



Since Container
doesn't have pack method, the compiler's gonna complain. You'll need to cast to JFrame
to make it
work:



((JFrame)SwingUtilities.getAncestorOfClass(JFrame.class,
this)).pack();



Careful,
though... The method can return null if no suitable ancestor was found. You might want
to check that first.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...