在 JPanels 限制内移动 JLabel(认为这是一个数学问题)JAVA

Moving A JLabel Within A JPanels Limit (Think Its A Math Problem) JAVA

这也可能有助于其他想要移动 JLabel 的人。

情况是这样的:

  1. 1 个包含项目的 JPanel。
  2. 1 个以 Img 作为 ICON 的 JLabel。
  3. 我想在面板周围移动 JLabel 但不要超出面板范围(这样用户就可以在屏幕上看到所有图像)

代码如下: 我在那里初始化:

int randH = 0;
int randW = 0;
int targetHeight = 0;
int targetWidth = 0;

然后面板打开时取决于加载的(目标/IMG):

    targetHeight = jLabel1.getHeight();
    targetWidth = jLabel1.getWidth();

然后当点击标签时,我调用了这段代码来移动它:

                int posH = jPanel1.getHeight() - targetHeight;
                int posW = jPanel1.getWidth() - targetWidth;

                randH = new Random().nextInt(posH) - jLabel1.getHeight();
                randW = new Random().nextInt(posW) - jLabel1.getWidth();

                if (randH <= 0) {

                    int num = (int) (Math.random() * 5);;
                    randH = num;
                }

                if (randW <= 0) {

                    int num = (int) (Math.random() * 5);;
                    randW = num;
                }
                if (randH >= posH) {

                    int num = (int) (Math.random() * 5);;
                    randH = posH - num;
                }

                if (randW >= posW) {

                    int num = (int) (Math.random() * 5);;
                    randW = posW - num;
                }
                jPanel1.setLayout(null);
                jLabel1.setBounds(new Rectangle(new Point(200, 300), jLabel1.getPreferredSize()));
                jLabel1.setLocation(randW, randH);

                jLabel1.setVisible(true);

因此当值大于 JPanel 的尺寸时,有时 IMG 会部分超出面板

有什么原因吗?

检查完毕,感谢大家的帮助!

randH = new Random().nextInt((posH - 0) + 1) + 0;

似乎已经把我带到了我需要去的地方

posH = is the max value
0 = is the min value 
+1 = include max
+0 = include min

再解释一下,下面的代码是为了确保 IMG 没有紧贴面板边框,因此图像和边框之间至少有 5 个像素。

                if (randH <= 0) {

                    int num = (int) (Math.random() * 5);;
                    randH = num;
                }

                if (randW <= 0) {

                    int num = (int) (Math.random() * 5);;
                    randW = num;
                }
                if (randH >= posH) {

                    int num = (int) (Math.random() * 5);;
                    randH = posH - num;
                }

                if (randW >= posW) {

                    int num = (int) (Math.random() * 5);;
                    randW = posW - num;
                }

据我所知,可能做得不好 :D