Display image in Java JFrame

笑着哭i 提交于 2019-12-10 12:58:51

问题


What's the best way to display an image at specific coordinates in a java JFrame?

I know there are a number of ways to do this, I just need to know the best way to display an image that I am planning on moving around the frame!


回答1:


I would suggest adding it as an ImageIcon:

ImageIcon image = new ImageIcon("image.jpeg");
add(image);

EDIT (How to add it add specific coordinates):

First a note, usually (99% of the cases) it is NOT encouraged to position JComponents yourself. Use a LayoutManager to position them for you, and handle the resizing.
I will tell you how to position it yourself though:

  • Set your LayoutManager to null: setLayout(null).
  • set your ImageIcon to specific coordinates: image.setLocation(x, y).



回答2:


Using an ImageIcon with a JLabel is the easiest way. You can actually add this to a level in JFrame's JLayeredPane that is above or below the contentPane depending on your requirements




回答3:


Develop a custom component and override paintComponent() method to do this. Developing a custom component gives you flexibility for further enhancements. You can add panning, zooming, etc type of capabilities easily this way.

Then just add this component to your JFrame.



来源:https://stackoverflow.com/questions/10806310/display-image-in-java-jframe

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