简体   繁体   English

Java Swing:设置可点击背景图像的最佳方法

[英]Java Swing : best way to set background image clickable

I try to find the best way to make an image clickable with different action depending on the area you click. 我尝试找到使图像可点击的最佳方法,具体取决于您点击的区域。 For now, my window display an EFTPOS (image found on google image) using : 现在,我的窗口使用以下命令显示一个EFTPOS(在Google图片上找到的图片):

 getContentPane().add(new JPanelBackground("./img/background.png", "./img/eftposAboveBackground.png", this.getWidth(), this.getHeight()));

Now, I would like to click on every EFTPOS's buttons. 现在,我想单击每个EFTPOS的按钮。 I was thinking of create some transparent buttons at the buttons's positions but : 我正在考虑在按钮的位置创建一些透明按钮,但是:

  • First, I don't want to use an absolute layer 首先,我不想使用绝对图层
  • Second, the Swing GUI design editor (Netbeans) doesn't display my background image since I used the code above. 其次,由于使用了上面的代码,Swing GUI设计编辑器(Netbeans)不显示我的背景图像。

I'm pretty sure there is another way than setting my eftpos on the background, maybe using the ImageIcon class.. 我很确定,除了在后台设置我的eftpos之外,还有另一种方法,也许使用ImageIcon类。

Any help would be greatly appreciated! 任何帮助将不胜感激!

  1. You can to create an ArrayList of Rectangles (or Shapes) to represent the area of each button on the image. 您可以创建Rectangles (或形状)的ArrayList来表示图像上每个按钮的区域。
  2. You need to add a MouseListener to the image. 您需要将MouseListener添加到图像。
  3. In the mousePressed() event you need to iterate through all the Rectangle in the ArrayList using the Rectangle.contains(mouse point) method to see if the user clicked in a Rectangle. 在mousePressed()事件中,您需要使用Rectangle.contains(mouse point)方法遍历ArrayList中的所有Rectangle,以查看用户是否单击了Rectangle。
  4. When you find the Rectangle that was clicked you execute your custom code. 找到单击的矩形后,将执行自定义代码。

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

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