井字游戏我无法设置 x 按钮的边界

Tic-Tac-Toe I can't setBounds of the x button

在我的 Tic-Tac-Toe 游戏中,我已经绘制了线条,现在正尝试放入按钮。我试图放入的第一个按钮,我试图设置边界,但它没有设置边界。它只是填满了整个屏幕。如何让 button 只出现在右上角的方块中?

public class Project extends JFrame{

static JButton button = new JButton("");
static JButton button2 = new JButton("");
static JButton button3 = new JButton("");
static JButton button4 = new JButton("");
static JButton button5 = new JButton("");
static JButton button6 = new JButton("");
static JButton button7 = new JButton("");
static JButton button8 = new JButton("");
static JButton button9 = new JButton("");


    public Project(){
        setSize(1000, 750);
    }

    public void paint(Graphics g){
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        Line2D line = new Line2D.Float(100, 100, 100, 400);
        Line2D line2 = new Line2D.Float(200, 100, 200, 400);
        Line2D line3 = new Line2D.Float(0, 200, 300, 200);
        Line2D line4 = new Line2D.Float(0, 300, 300, 300);
        g2.draw(line);
        g2.draw(line2);
        g2.draw(line3);
        g2.draw(line4);
    }

    public static void main(String[] args){
        Project t = new Project();
        t.setVisible(true);
        button.setBounds(0, 0, 50, 50);
        t.add(button);
    }
}

你的项目class扩展了JFrame,JFrame contentPane,接受新组件的JFrame容器,默认使用BorderLayout。当您将组件添加到使用 BorderLayout 的容器而没有指定组件的位置时,默认情况下它会添加到 BorderLayout.CENTER 位置,从而有效地填充您的 GUI。有几个选项可以解决您的难题:

  • 按照 PM77-1 的建议使用 GridLayout。这样,一个 3x3 的网格将在大小相等的单元格中容纳所有 9 个按钮,填满容器。
  • 根本不使用按钮和 ActionListeners,而是使用 MouseListenerListener 来检查按钮按下的位置,确定它是否为空单元格,并采取相应的行动。