Wednesday 12 December 2018

java - Resize JFrame according to JPanel image content?



I'm using NetBeans to develop a simple image browser. I have the class ImageBrowser which extends JFrame (created it by right clicking the NetBeans project then New -> JFrame Form) and inside it is a JPanel and a JToolbar with JButtons generated as image thumbnails from a directory the user selects.



Clicking an image thumbnail displays the image as a whole on this main JPanel. Basically the images are of different sizes and I want the JFrame (ie. entire window) to automatically adjust to the size of the image.




I've tried calling .pack() for the main `JFrame' every time the JPanel content changes (ie. when the user clicks a thumbnail and fires an ActionEvent), but it's giving me this error:




non-static method pack() cannot be referenced from static content




So I'm rather stuck on this and I'm wondering if there's a way to do it. If there is, is it also possible to set a maximum limit on the JFrame window size?



As for layout, the JFrame is a free layout, constructed using the NetBeans GUI developer.


Answer





non-static method pack() cannot be referenced from static content




Don't use static methods in your application. There is no need to do this. The only static method should be the main() method and the "createAndShowGUI" method assuming you follow the example code found in the Swing tutorial examples.



You can find the Window to pack() by using



SwingUtilities.windowForComponent(...);



You get the source from the ActionEvent and then use that component to find the Window to pack.




is it also possible to set a maximum limit on the JFrame window size?




Do the pack(). Then you can always overide the maximum size by invoking setSize() on the Window if the dimensions exceed you limit.



I also agree, it is not a good design to continually have the size of the Window change each time the image is changed.




I would add the Image to a JLabel and add the label to a scrollpane to that scrollbar can appear when the image is greater than the size of the frame.


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...