简体   繁体   English

如何在Java Swing中创建响应式JList

[英]How can I create responsive JList in Java Swing

I want to create a shop by having a main JPanel that each component inside it is a JPanel with an image, label and button. 我想通过拥有一个主JPanel来创建商店,其中的每个内部组件都是一个具有图像,标签和按钮的JPanel

I did tried using a JList but the problem with the JList its only holds the rendering of the component and because of that the button isn't working and its only an image. 使用我没有尝试过JList但随着问题JList其仅持有该组件的渲染,因为该按钮没有工作,其唯一的图像和。 I can walk around and use MouseEvent but it feels wrong for me and I am sure that there is a better solution for it. 我可以四处走动并使用MouseEvent,但对我来说这是错的,我相信有更好的解决方案。

I want that the components will change their positions depend on the frame size, like in the JList . 我希望组件将根据框架大小更改其位置,例如JList

For example, if I change from the width of the screen the positions of the components will change from this: 例如,如果我从屏幕的宽度更改,组件的位置将由此改变:

在此处输入图片说明

to this: 对此:

在此处输入图片说明

I do have an idea by using GridLayout or GridBagLayout in the paintComponent (because it calls every rendering. If you know another method that calls every rendering int the JPanel I would like to know) and changing the positions of the components by changing the layout variables inside the paintComponent . 我确实有一个想法,可以在paintComponent使用GridLayoutGridBagLayout (因为它调用每个渲染。如果您知道另一个我想知道的调用JPanel每个渲染int的方法),并通过更改布局变量来更改组件的位置在paintComponent内部。

I did surfed the internet to find a solution but I only found that people used JTable but I don't see it working here. 我确实浏览了互联网以找到解决方案,但我只发现人们使用了JTable但我看不到它在这里起作用。

each component inside it is a JPanel with an image, label and button. 其中的每个组件都是一个带有图像,标签和按钮的JPanel。

Makes sense. 说得通。

changing the positions of the components by changing the layout variables inside the paintComponent. 通过更改paintComponent内部的布局变量来更改组件的位置。

The paintComponent() method has nothing to do with changing the layout of the panels. paintComponent()方法与更改面板的布局无关。 You should not be playing with the paintComponent() method. 您不应该使用paintComponent()方法。

I do have an idea by using GridLayout or GridBagLayout 我确实有使用GridLayout或GridBagLayout的想法

You are correct to use a layout manager, but unfortunately, none of the default layout managers will wrap automatically at a random number of components. 使用布局管理器是正确的,但是不幸的是,没有默认布局管理器会自动包装随机数量的组件。

The layout managers are invoked automatically as the frame is resized. 调整框架大小时,将自动调用布局管理器。

So you can use the Wrap Layout which is an extension to the FlowLayout that will allow random wrapping. 因此,您可以使用Wrap Layout ,这是FlowLayout的扩展,允许随机包装。

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

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