java - 在形状上画一条绳子

标签 java swing

我有一个椭圆形,我想为我的国际象棋游戏标记它是什么。我想使用椭圆形,并将其上的碎片名称作为字符串,但我似乎无法让它工作。

是否可以在形状上绘制字符串?

我的代码

    public void drawPieces(Graphics2D g2d){
    for(int x = 0; x < 8; x++) {
        for(int y = 0; y < 8; y++) {
        //reds
        if(board[x][y]==24){
            g2d.setColor(Color.red);
            g2d.fillOval(x*80, y*80, 80, 80);
            //drawstring goes here
                            g2d.setColor(Color.blue);
                            g2d.drawString("test", x*80, y*80);
        }

欢迎提出建议

编辑我的网格方法,以防有帮助。

    public void drawGrid(Graphics2D g2d){


    g2d.drawLine(0, 0, 0, 639);
    g2d.drawLine(0, 0, 639, 0);
    g2d.drawLine(0, 639, 639, 639);
    g2d.drawLine(639, 0, 639, 639);

    // draw the horizontal lines using a loop from one to 7, coordiates of each line is (0, x*80, 640, x*80) also
    // draw vertical lines with coordinates of (x*80, 0, x*80, 640)
    for(int i = 1; i < 8; i++) {
        g2d.drawLine(0, i*80, 640, i*80);
        g2d.drawLine(i*80, 0, i*80, 640);
    }
    //drawing the black and white squares 
    for (int row = 0; row < 8; row++)
        for (int col = 0; col < 8; col++) {
            if ( (row % 2 == 0 && col % 2 == 0) ||  ( row % 2 == 1 &&  col % 2 == 1)  ){
                g2d.setColor(black);
                g2d.fillRect(row*80,col*80,80,80);

            }
        }
}

最佳答案

我只能说可以在椭圆形上画一根绳子,而且我在自己的游戏中就是这么做的。顶部绘图代码应该没问题。您只需要检查传递给绘图方法的参数和 if 条件。这是我绘制的代码的摘录 使用稍微不同的方法在椭圆形上,但你也应该工作:

public void draw(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    g2d.fill(new Ellipse2D.Double(center.x, center.y, itemSize, itemSize));
    g2d.setColor(Color.white);
    g2d.setFont(new Font("Arial", Font.BOLD, 14));
    g2d.drawString(itemName, (int)center.x, (int)center.y+18);
}

itemName 是一些字符串,只是为了不要混淆,我认为前两个参数是

g2d.fill(...(-,-,itemSize, itemSize)) 不是椭圆的中心,而是其周围矩形的左上角。

关于java - 在形状上画一条绳子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20502531/

相关文章:

java - 使用上下文菜单捕获 HWND

java - 无法在我的本地主机上运行 Apache Tomcat 服务器?

java - 方法和最终修饰符

java - 堆叠 JLayer 类(到 JPanel)

java - 如何在JLayeredPane的任意一层上使用图形(Piant组件)

java - 存储配置数据的最佳实践

java - 如何从Java连接到MySQL而不将密码存储为明文

java - Spring Boot Shutdown Hook 中途终止

java - 如何停止执行表达式的程序?

java - 未检测到 JMenuItem Actionlistener