You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swing中如何绘制带有3D坐标系的立方体?

解决Swing中3D坐标系的绘制问题

我已经用Swing实现了立方体的绘制,现在需要为其添加3D坐标系。预期的坐标系是带有X、Y、Z三个轴的3D效果,但目前仅能画出X、Y轴,不清楚如何添加Z轴,实际效果和预期差距较大。现有代码如下:

import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;

public class Cube extends JPanel {
    double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
            {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};

    int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
            {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};

    public Cube() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);

        scale(50);
        rotateCube(Math.toRadians(60), Math.toRadians(10), Math.toRadians(0));
    }

    final void scale(double s) {
        for (double[] node : nodes) {
            node[0] *= s;
            node[1] *= s;
            node[2] *= s;
        }
    }

    final void rotateCube(double angleX, double angleY, double angleZ) {
        double sinX = sin(angleX);
        double cosX = cos(angleX);

        double sinY = sin(angleY);
        double cosY = cos(angleY);

        double sinZ = sin(angleZ);
        double cosZ = cos(angleZ);

        for (double[] node : nodes) {
            double x = node[0];
            double y = node[1];
            double z = node[2];

            node[0] = x * cosX - z * sinX;
            node[2] = z * cosX + x * sinX;

            z = node[2];

            node[1] = y * cosY - z * sinY;
            node[2] = y * sinY + z * cosY;

            x = node[0];
            y = node[1];

            node[0] = x * cosZ + y * sinZ;
            node[1] = y * cosZ - x * sinZ;
        }
    }

    void drawCube(Graphics2D g) {
        g.translate(getWidth() / 2, getHeight() / 2);

        g.setColor(Color.BLACK);
        for (int[] edge : edges) {
            double[] xy1 = nodes[edge[0]];
            double[] xy2 = nodes[edge[1]];
            g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
                    (int) round(xy2[0]), (int) round(xy2[1]));
        }

        for (double[] node : nodes)
            g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);
    }

    void drawAxis(Graphics2D g) {
        int x_c = getWidth() / 2;
        int y_c = getHeight() / 2;

        // X - axis
        g.setColor(Color.green);
        g.drawLine(round(x_c + 300), round(y_c), round(x_c), round(y_c));

        // Y- axis
        g.setColor(Color.blue);
        g.drawLine(round(x_c), round(y_c), round(x_c), round(y_c) + 300);
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawAxis(g);
        drawCube(g);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Rotating Cube");
            f.setResizable(false);
            f.add(new Cube(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}

问题核心与解决方案

当前坐标系绘制的问题在于:轴线是直接基于屏幕坐标绘制的,没有和立方体共享3D变换逻辑,导致坐标系和立方体不在同一3D空间,无法呈现正确的Z轴效果。以下是修正后的完整代码:

import java.awt.*;
import static java.lang.Math.*;
import javax.swing.*;

public class Cube extends JPanel {
    double[][] nodes = {{-1, -1, -1}, {-1, -1, 1}, {-1, 1, -1}, {-1, 1, 1},
            {1, -1, -1}, {1, -1, 1}, {1, 1, -1}, {1, 1, 1}};

    int[][] edges = {{0, 1}, {1, 3}, {3, 2}, {2, 0}, {4, 5}, {5, 7}, {7, 6},
            {6, 4}, {0, 4}, {1, 5}, {2, 6}, {3, 7}};

    // 新增:坐标系节点(原点+X/Y/Z轴端点)
    double[][] axisNodes = {{0, 0, 0}, {300, 0, 0}, {0, 300, 0}, {0, 0, 300}};

    public Cube() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);

        scale(50);
        rotateCube(Math.toRadians(60), Math.toRadians(10), Math.toRadians(0));
        // 对坐标系应用相同的旋转变换
        rotateAxis(Math.toRadians(60), Math.toRadians(10), Math.toRadians(0));
    }

    final void scale(double s) {
        for (double[] node : nodes) {
            node[0] *= s;
            node[1] *= s;
            node[2] *= s;
        }
    }

    final void rotateCube(double angleX, double angleY, double angleZ) {
        double sinX = sin(angleX);
        double cosX = cos(angleX);

        double sinY = sin(angleY);
        double cosY = cos(angleY);

        double sinZ = sin(angleZ);
        double cosZ = cos(angleZ);

        for (double[] node : nodes) {
            double x = node[0];
            double y = node[1];
            double z = node[2];

            node[0] = x * cosX - z * sinX;
            node[2] = z * cosX + x * sinX;

            z = node[2];

            node[1] = y * cosY - z * sinY;
            node[2] = y * sinY + z * cosY;

            x = node[0];
            y = node[1];

            node[0] = x * cosZ + y * sinZ;
            node[1] = y * cosZ - x * sinZ;
        }
    }

    // 新增:坐标系旋转方法,和立方体旋转逻辑完全一致
    final void rotateAxis(double angleX, double angleY, double angleZ) {
        double sinX = sin(angleX);
        double cosX = cos(angleX);

        double sinY = sin(angleY);
        double cosY = cos(angleY);

        double sinZ = sin(angleZ);
        double cosZ = cos(angleZ);

        for (double[] node : axisNodes) {
            double x = node[0];
            double y = node[1];
            double z = node[2];

            node[0] = x * cosX - z * sinX;
            node[2] = z * cosX + x * sinX;

            z = node[2];

            node[1] = y * cosY - z * sinY;
            node[2] = y * sinY + z * cosY;

            x = node[0];
            y = node[1];

            node[0] = x * cosZ + y * sinZ;
            node[1] = y * cosZ - x * sinZ;
        }
    }

    void drawCube(Graphics2D g) {
        g.translate(getWidth() / 2, getHeight() / 2);

        g.setColor(Color.BLACK);
        for (int[] edge : edges) {
            double[] xy1 = nodes[edge[0]];
            double[] xy2 = nodes[edge[1]];
            g.drawLine((int) round(xy1[0]), (int) round(xy1[1]),
                    (int) round(xy2[0]), (int) round(xy2[1]));
        }

        for (double[] node : nodes)
            g.fillOval((int) round(node[0]) - 4, (int) round(node[1]) - 4, 8, 8);
    }

    // 修改:基于3D变换后的节点绘制坐标系
    void drawAxis(Graphics2D g) {
        g.translate(getWidth() / 2, getHeight() / 2);

        // X轴(绿色)
        g.setColor(Color.GREEN);
        g.drawLine((int)round(axisNodes[0][0]), (int)round(axisNodes[0][1]),
                   (int)round(axisNodes[1][0]), (int)round(axisNodes[1][1]));
        // Y轴(蓝色)
        g.setColor(Color.BLUE);
        g.drawLine((int)round(axisNodes[0][0]), (int)round(axisNodes[0][1]),
                   (int)round(axisNodes[2][0]), (int)round(axisNodes[2][1]));
        // Z轴(红色)
        g.setColor(Color.RED);
        g.drawLine((int)round(axisNodes[0][0]), (int)round(axisNodes[0][1]),
                   (int)round(axisNodes[3][0]), (int)round(axisNodes[3][1]));
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawAxis(g);
        drawCube(g);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Rotating Cube");
            f.setResizable(false);
            f.add(new Cube(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}

关键修改点

  1. 添加坐标系3D节点:定义axisNodes数组,包含原点和三个轴的端点,让坐标系和立方体处于同一3D空间。
  2. 统一变换逻辑:新增rotateAxis方法,复用立方体的旋转逻辑,保证坐标系和立方体同步旋转,呈现一致的3D视角。
  3. 重构绘制逻辑:修改drawAxis方法,基于变换后的3D节点绘制轴线,Z轴会自动呈现正确的透视效果。

内容的提问来源于stack exchange,提问作者annd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:45:43