我目前正在制作一个可通过GUI设置棋盘的程序。我的问题是我可以设置面板颜色,并使程序在单击鼠标时以及在何处单击时通知我,但是我不知道如何使棋盘格出现在正确位置的每个位置的中间。

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class Main {
    public static int rows = 8;
    public static int colums = 8;
    public static Color Col1 = Color.BLACK;
    public static Color Col2 = Color.RED;

    public static void main(String [ ] args){
        System.out.println("Dbug3");
        JFrame boardGUI = new JFrame();
        boardGUI.setSize(800, 800);
        boardGUI.setTitle("Checker Board");
        Container pane = boardGUI.getContentPane();
        pane.setLayout(new GridLayout(rows, colums));
        Color tmp;
        ImageIcon image = new ImageIcon("C:\\Users\\Awesome\\Desktop\\CheckerP.jpg");

        JLabel label = new JLabel("", image, JLabel.CENTER);

        boardGUI.addMouseListener(new MouseAdapter() {

            public void mousePressed(MouseEvent e) {
                //Board
                System.out.println(e.getX() + "," + e.getY());
            }
        });
        for (int i = 0; i < rows; i++) {
            if (i % 2 == 0) {
                tmp = Col1;
            } else {
                tmp = Col2;
            }
            for (int j = 0; j < colums; j++) {
                JPanel panel = new JPanel();
                panel.setBackground(tmp);
                panel.add( label, BorderLayout.CENTER );
                if (tmp.equals(Col1)) tmp = Col2;
                else tmp = Col1;
                pane.add(panel);
            }


        }
        boardGUI.setVisible(true);

    }
    public void paint(Graphics2D g) {
        g.fillOval(480,480,200,200);
        g.setColor(Color.BLUE);
    }
}

最佳答案

drawOval之前尝试使用fillOval

 public void drawCircle(Graphics2D g) {
        g.drawOval(480, 480, 200, 200);
        g.setColor(Color.BLUE);
        g.fillOval(480, 480, 200, 200);
    }

10-04 15:38