Java 如何在秋千中创建一个立方体?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22549690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:25:04  来源:igfitidea点击:

How to create a cube in swing?

javaswinggraphicsjpanelcube

提问by SemperAmbroscus

I am trying to make a class that when invoked by a JPanel, creates a cube. What I have seen though, is something called a ColorCube, which requires a "Universe" of some sort, and a Canvas, though I didn't find this method to be compatible with JPanel.

我正在尝试创建一个类,当被 a 调用时JPanel,会创建一个多维数据集。不过,我所看到的是一种叫做 a 的东西ColorCube,它需要某种“ Universe”和 a Canvas,尽管我没有发现这种方法与JPanel.

TO clarify, I am not asking how to create a custom JComponent(exactly), nor am I asking how to add color or rotate it, just how to create a class that when invoked by a JPanelrenders a cube to the screen.

澄清一下,我不是在问如何创建自定义JComponent(确切地说),也不是在问如何添加颜色或旋转它,只是问如何创建一个类,当被 a 调用时JPanel将立方体呈现到屏幕上。

采纳答案by Paul Samsotha

All you really need are x, y, and sizepassed to the Cubeclass, then

所有你真正需要的都x, y, and size传递给了Cube班级,然后

  • Take those arguments and build an array of corners points for a first square and also corner points for a second shifted square. See methods getCubeOnePointsand getCubeTwoPointsmethods in the Cubeclass.

  • Draw the first square. Draw the second square, and connect the points from the point arrays. See the drawCubemethod in the Cubeclass.

  • Create an instance of the Cubeclass passing necessary arguments, and draw the cube. See CubePanelconstructor and paintComponentmethod

  • 接受这些参数并为第一个正方形构建一个角点数组,并为第二个移动的正方形构建一个角点。查看类中的方法getCubeOnePointsgetCubeTwoPoints方法Cube

  • 绘制第一个正方形。绘制第二个正方形,并连接点数组中的点。查看类中的drawCube方法Cube

  • 创建Cube传递必要参数的类的实例,并绘制立方体。见CubePanel构造函数和paintComponent方法

enter image description here

在此处输入图片说明

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class CubePanel extends JPanel{
    private static final int D_W = 400;
    private static final int D_H = 400;

    Cube cube;
    public CubePanel() {
        cube = new Cube(75, 75, 200, 50);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        cube.drawCube(g);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_W, D_H);
    }

    public class Cube {
        int x, y, size, shift;
        Point[] cubeOnePoints;
        Point[] cubeTwoPoints;
        public Cube(int x, int y, int size, int shift) {
            this.x = x;
            this.y = y;
            this.size = size;
            this.shift = shift;
            cubeOnePoints = getCubeOnePoints();
            cubeTwoPoints = getCubeTwoPoints();
        }

        private Point[] getCubeOnePoints() {
            Point[] points = new Point[4];
            points[0] = new Point(x, y);
            points[1] = new Point(x + size, y);
            points[2] = new Point(x + size, y + size);
            points[3] = new Point(x, y + size);
            return points;
        }

        private Point[] getCubeTwoPoints() {
            int newX = x + shift;
            int newY = y + shift;
            Point[] points = new Point[4];
            points[0] = new Point(newX, newY);
            points[1] = new Point(newX + size, newY);
            points[2] = new Point(newX + size, newY + size);
            points[3] = new Point(newX, newY + size);
            return points;
        }

        public void drawCube(Graphics g) {
            g.drawRect(x, y, size, size);
            g.drawRect(x + shift, y + shift, size, size);
            // draw connecting lines
            for (int i = 0; i < 4; i++) {
                g.drawLine(cubeOnePoints[i].x, cubeOnePoints[i].y, 
                        cubeTwoPoints[i].x, cubeTwoPoints[i].y);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new CubePanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}


UPDATE

更新

"what if i wanted this in a 3d where the cube could be walked around "

“如果我想要在立方体可以四处走动的 3d 中,该怎么办?”

Just create methods to shift allthe xs or ys and call it, then repaint. The method could look something like

只要创建方法转移所有xS或yS和调用它,然后重新绘制。该方法可能看起来像

    public void shiftLeft() {
        x -= SHIFT_INC;
        for (Point p : cubeOnePoints) {
            p.x -= SHIFT_INC;
        }
        for (Point p : cubeTwoPoints) {
            p.x -= SHIFT_INC;
        }
    }

In the example below, I just call it in a key bind with the key.

在下面的示例中,我只是在与键的键绑定中调用它

    im.put(KeyStroke.getKeyStroke("LEFT"), "shiftLeft");
    getActionMap().put("shiftLeft", new AbstractAction(){
        public void actionPerformed(ActionEvent e) {
            cube.shiftLeft();
            repaint();
        }
    });

enter image description here

在此处输入图片说明

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class CubePanel extends JPanel{
    private static final int D_W = 400;
    private static final int D_H = 300;

    Cube cube;
    public CubePanel() {
        cube = new Cube(75, 75, 50, 15);
        InputMap im = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        im.put(KeyStroke.getKeyStroke("RIGHT"), "shiftRight");
        getActionMap().put("shiftRight", new AbstractAction(){
            public void actionPerformed(ActionEvent e) {
                cube.shiftRight();
                repaint();
            }
        });
        im.put(KeyStroke.getKeyStroke("LEFT"), "shiftLeft");
        getActionMap().put("shiftLeft", new AbstractAction(){
            public void actionPerformed(ActionEvent e) {
                cube.shiftLeft();
                repaint();
            }
        });
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        cube.drawCube(g);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(D_W, D_H);
    }

    public class Cube {
        private static final int SHIFT_INC = 5;
        int x, y, size, shift;
        Point[] cubeOnePoints;
        Point[] cubeTwoPoints;
        public Cube(int x, int y, int size, int shift) {
            this.x = x;
            this.y = y;
            this.size = size;
            this.shift = shift;
            cubeOnePoints = getCubeOnePoints();
            cubeTwoPoints = getCubeTwoPoints();
        }

        private Point[] getCubeOnePoints() {
            Point[] points = new Point[4];
            points[0] = new Point(x, y);
            points[1] = new Point(x + size, y);
            points[2] = new Point(x + size, y + size);
            points[3] = new Point(x, y + size);
            return points;
        }

        private Point[] getCubeTwoPoints() {
            int newX = x + shift;
            int newY = y + shift;
            Point[] points = new Point[4];
            points[0] = new Point(newX, newY);
            points[1] = new Point(newX + size, newY);
            points[2] = new Point(newX + size, newY + size);
            points[3] = new Point(newX, newY + size);
            return points;
        }

        public void shiftLeft() {
            x -= SHIFT_INC;
            for (Point p : cubeOnePoints) {
                p.x -= SHIFT_INC;
            }
            for (Point p : cubeTwoPoints) {
                p.x -= SHIFT_INC;
            }
        }

        public void shiftRight() {
            x += SHIFT_INC;
            for (Point p : cubeOnePoints) {
                p.x += SHIFT_INC;
            }
            for (Point p : cubeTwoPoints) {
                p.x += SHIFT_INC;
            }
        }

        public void drawCube(Graphics g) {
            g.drawRect(x, y, size, size);
            g.drawRect(x + shift, y + shift, size, size);
            // draw connecting lines
            for (int i = 0; i < 4; i++) {
                g.drawLine(cubeOnePoints[i].x, cubeOnePoints[i].y, 
                        cubeTwoPoints[i].x, cubeTwoPoints[i].y);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new CubePanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

回答by ProgRoger

package Box;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
public class Box2 extends JPanel
{

    public Box2() 
    {
        this.addComponentListener(new ComponentListener(){
        public void componentShown(ComponentEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void componentResized(ComponentEvent arg0) {
            paintComponent(getGraphics());

        }

        public void componentMoved(ComponentEvent arg0) {
            // TODO Auto-generated method stub

        }

        public void componentHidden(ComponentEvent arg0) {
            // TODO Auto-generated method stub

        }
        });

    }
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        this.setBackground(Color.white);


        Dimension d;
        d=getSize();
        int height, width;
        height =d.height;
        width=d.width;
        int w,h;
        javax.swing.border.Border linebor =BorderFactory.createLineBorder(new Color(0xAD85FF),6 );

        g.drawRect(0,0, w=width/2, h=height/2);

        g.drawRect(w/2,h/2,w/2*2,h/2*2);

        g.drawLine(0,0,w/2,h/2);

        g.drawLine(w,h,w/2+w/2*2,h/2+h/2*2);

        g.drawLine(w,0,w/2+w/2*2,h/2);  

        g.drawLine(0,h,w/2,h/2+h/2*2);  
        //g.drawLine(0, height – borderControl, width, height – borderControl);
    }
}

Now make another class for Main File

现在为主文件创建另一个类

package Box;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Box2_main extends JPanel
{


    public static void main(String[] args)
    {
        Box2 cube = new Box2();
        JFrame frame = new JFrame("Cube2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(cube);
        frame.setSize(500, 500);
        frame.setVisible(true);
    }

}

If you change the dimensions of the window then the size of the cube will also increase/decrease.

如果您更改窗口的尺寸,则立方体的大小也会增加/减少。