How to put an image in a specific JPanel?

安稳与你 提交于 2019-12-06 09:23:44

To show a chip in a JPanel cell:

  • Put the chip image into an ImageIcon
  • Put that ImageIcon into a JLabel via JLabel's setIcon(chipIcon) method
  • Add the JLabel to the JPanel via the add(someLabel) method -- and the JPanel now will display the image.

Then if you want to click and move the chip,

  • give it MouseListener and MouseMotionListener (MouseAdapater)
  • When clicked, remove the JLabel from its containing JPanel and elevate it to the top level window's glass pane.
  • Move it with the MouseAdapter.
  • When released, place the JLabel the JPanel that the mouse is over.
  1. Set the size, manually, of each of the JPanel in the board to be as large as the image plus some padding if you choose.
  2. Maintain a 2d array containing your JPanels.
  3. Call repaint() on your JPanels whenever the user clicks on it. Do not forget to overrride the paintComponent() where you draw the image onto the JPanel

Here is how you might do the painting of image:

JPanel onePanel = new JPanel(){
                                @Override
                                public void paintComponent(Graphics g){
                                    super.paintComponent(g);
                                    g.drawImage(image,0,0,null);
                                }
                            }    

In the snippet above, I have created a custom JPanel so as to suit the needs.

So, lets say the user clicks on the first JPanel which is on position (0 , 0). You retrieve the JPanel from the board[][] and call repaint() on it. This will result in the image being drawn.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!