Java : JButton 的随机位置

Java : Random Position of JButton

我想用坐标设置 JButton 的位置,但如何使每个按钮不 "touch" 其他按钮?布局必须为空!!!我尝试了 contains 和 with Rectangle 的方法,但它没有用。

谢谢

假设您总共有 space 个 H 像素 x W 像素。 您可以将此 space 分成 10 x 10 的网格。
每个 "slot" 现在由 W/10 变成 H/10。
现在您可以使用空布局在每个插槽中使用随机 setBounds(...) 创建 100 个不会发生碰撞的按钮。
每个 JButton 都有自己的 space 并且您仍然会获得半随机性。

请注意,MadProgrammer 很可能会告诉您使用空布局是一个非常糟糕的主意。

编辑:
不仅 MadProgrammer。

免责声明:
我曾经为 JDekstopPane 使用过空布局。 我还有这行代码。
其余1M左右的代码没有这种叛逆的概念。

您将要使用 intersects(),而不是 contains()。如果 comp1 完全 包含 comp2contains() 只会 return true。这是一个继续在随机位置添加新 JButton 的示例,只要它们不与另一个 Component 相交即可。 (单击 here 进行预览)

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Example {

    private final int BUTTON_WIDTH = 100;
    private final int BUTTON_HEIGHT = 20;

    public Example() {
        JFrame frame = new JFrame();
        frame.setLayout(null);

        Timer timer = new Timer(100, new ActionListener() {
            Random random = new Random();

            @Override
            public void actionPerformed(ActionEvent arg0) {
                JButton button = new JButton("Button");
                button.setBounds(random.nextInt(frame.getContentPane().getWidth() - BUTTON_WIDTH),
                        random.nextInt(frame.getContentPane().getHeight() - BUTTON_HEIGHT), BUTTON_WIDTH,
                        BUTTON_HEIGHT);
                for (int tries = 0; tries < 50; tries++) {
                    if (intersectsComponent(button, frame.getContentPane().getComponents())) {
                        button.setBounds(random.nextInt(frame.getContentPane().getWidth() - BUTTON_WIDTH),
                                random.nextInt(frame.getContentPane().getHeight() - BUTTON_HEIGHT), BUTTON_WIDTH,
                                BUTTON_HEIGHT);
                    } else {
                        frame.add(button);
                        break;
                    }
                }
                frame.revalidate();
                frame.repaint();
            }
        });
        timer.start();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 600);
        frame.setVisible(true);
    }

    public boolean intersectsComponent(Component component, Component[] components) {
        for (Component c : components) {
            if (c.getBounds().intersects(component.getBounds())) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Example();
            }
        });
    }
}