简体   繁体   English

根据JPanel图片内容调整JFrame的大小?

[英]Resize JFrame according to JPanel image content?

I'm using NetBeans to develop a simple image browser. 我正在使用NetBeans开发一个简单的图像浏览器。 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. 我有ImageBrowser类,它扩展了JFrame (通过右键单击NetBeans项目,然后单击“新建”->“ JFrame窗体”来创建它),并且在其中是一个JPanel和一个JToolbar其中JButtons是从用户选择的目录中生成的图像缩略图。

Clicking an image thumbnail displays the image as a whole on this main JPanel . 单击图像缩略图会在此主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. 基本上,图像大小不同,我希望JFrame (即整个窗口)自动调整为图像大小。

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: 我尝试每次JPanel内容更改时(即,当用户单击缩略图并触发ActionEvent时)为主JFrame调用.pack() ,但这给了我这个错误:

non-static method pack() cannot be referenced from static content 非静态方法pack()不能从静态内容中引用

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? 如果有,是否还可以设置JFrame窗口大小的最大限制?

As for layout, the JFrame is a free layout, constructed using the NetBeans GUI developer. 至于布局, JFrame是使用NetBeans GUI开发人员构造的免费布局。

non-static method pack() cannot be referenced from static content 非静态方法pack()不能从静态内容中引用

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 . 假设您遵循在Swing教程示例中找到的示例代码,则唯一的静态方法应该是main()方法和“ createAndShowGUI”方法。

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. 您可以从ActionEvent中获取源代码,然后使用该组件查找要打包的Window。

is it also possible to set a maximum limit on the JFrame window size? 是否还可以设置JFrame窗口大小的最大限制?

Do the pack(). 做pack()。 Then you can always overide the maximum size by invoking setSize() on the Window if the dimensions exceed you limit. 然后,如果尺寸超出限制,则始终可以通过在Window上调用setSize()来覆盖最大尺寸。

I also agree, it is not a good design to continually have the size of the Window change each time the image is changed. 我也同意,每次更改图像时都要不断更改Window的大小并不是一个好的设计。

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. 我将图像添加到JLabel并将标签添加到滚动窗格,以使当图像大于框架大小时该滚动条可以显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM