简体   繁体   English

在Java中使用Swing定位标签

[英]Positioning a label using swing in java

I have been using jFrame to build a GUI. 我一直在使用jFrame来构建GUI。 I had to insert images in the GUI, for which i inserted a label and put the image as an icon for the label. 我必须在GUI中插入图像,为此我插入了标签并将图像作为标签的图标。 Now, i have to find out the position of the image in terms of the x and y co-ordinates and i am unable to do that. 现在,我必须根据x和y坐标找出图像的位置,而我无法做到这一点。 I have used 我用过

 setLocaction(x,y);

but it still doesn't seem to work. 但它似乎仍然不起作用。 I even disabled the layout manager by using 我什至通过使用禁用了布局管理器

 setLayout(null); 

What is the possible solution for this problem? 该问题的可能解决方案是什么?


Edit 编辑

Basically i am creating a Solar system GUI using Swing, so the positions of the planets are to be set by me. 基本上,我是使用Swing创建Solar System GUI的,所以行星的位置应由我来设置。 I being new to java, there is being some difficulty in implementing the layouts. 我是Java的新手,在实现布局方面有些困难。

This isn't a layout issue at all, but a drawing and possibly an animation issue. 这根本不是布局问题,而是图形甚至是动画问题。 If this were my project, I'd 如果这是我的项目,我会

  • First and foremost, separate out the program logic from its display, a la the MVC or Model-View-Control pattern, or one of its many variants. 首先,最重要的是,将程序逻辑与其显示(MVC或Model-View-Control模式,或其多种变体之一)分开。
  • Create one JPanel for the GUI's graphics and do all my drawing in this 为该GUI的图形创建一个JPanel并在此进行所有绘图
  • I would not display my planet images using ImageIcons inside of JLabels. 我不会在JLabels中使用ImageIcons显示我的星球图像。
  • Rather, I'd create a background image and draw my planet sprites inside of the drawing JPanel's paintComponent method. 相反,我将创建一个背景图像,并在绘图JPanel的paintComponent方法内部绘制我的星球精灵。
  • I'd create non-GUI Planet classes that a non-GUI model would hold. 我将创建一个非GUI模型可以容纳的非GUI Planet类。
  • In the GUI portion of my program, I would associate a BufferedImage with each Planet, probably using a HashMap<Plant, Image> . 在我程序的GUI部分中,我可能会使用HashMap<Plant, Image>将BufferedImage与每个Planet关联。
  • I'd then draw each Planet's associated image in the drawing JPanel's paintComponent(...) method, and place it depending on the Planet's position field values. 然后,我将在绘制JPanel的paintComponent(...)方法中绘制每个Planet的关联图像,并根据Planet的位置字段值进行放置。
  • If I wanted to animate this, I'd use a Swing Timer to drive my simple animation. 如果要对此进行动画处理,我将使用Swing计时器来驱动我的简单动画。

使用null布局时,应在标签上使用setSizesetLocation方法,以使图像在框架内正确可见。

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

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