Java turtle 图形用户输入

标签 java swing graphics2d turtle-graphics

我正在尝试用 Java 编写一个 turtle graphics 程序。它需要能够通过 JTextField 读取用户输入的命令来创建 2D 图形。我已经创建了GUI并为每个命令编写了不同的方法,例如turnRight、turnLeft、forward等,但是我遇到的问题是我在JTextField上创建了一个带有 Action 监听器的if/else语句,以便它可以识别用户给出的命令,并尝试在收到该文本时调用我编写的方法。尽管如此,程序仍然不会绘制,我不确定我做错了什么。任何帮助将不胜感激。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;



//Represents the graphics display panel within the turtle program. This panel contains an image which is updated to reflect user commands.

@SuppressWarnings("serial")
public class GraphicPanel extends JPanel 
{
    private int xPos = 0, yPos=0;
    private boolean penUp = true;
    private final static int DOWN = 0;
    private final static int UP = 1;
    private final static int LEFT = 2;
    private final static int RIGHT = 3;
    private int direction = DOWN;


GraphicPanel() {

    setPreferredSize(new Dimension(800, 600));

    image = new BufferedImage(700, 600, BufferedImage.TYPE_INT_RGB);

    // Set max size of the panel, so that is matches the max size of the image.
    setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));

    clear();

JTextField console = new JTextField(15);
    console.addActionListener(new ActionListener() 
    {
        public void actionPerformed(ActionEvent arg0) 
            {
                    if(console.getText().contains("penup")) {
                        penUp();
                    }

                    else if (console.getText().contains("pendown")) {
                        penDown();
                    }

                    else if (console.getText().contains("turnleft")) {
                      JOptionPane.showMessageDialog(console, "turnleft works");
                    }

                    else if (console.getText().contains("turnright")) {
                       JOptionPane.showMessageDialog(console, "turnright works");
                    }

                    else if (console.getText().contains("forward")) {
                        forward(direction);
                    }

                    else if (console.getText().contains("backward")) {
                       JOptionPane.showMessageDialog(console, "backward works");
                    }

                    else if (console.getText().contains("black")) {
                       JOptionPane.showMessageDialog(console, "black works");
                    }

                    else if (console.getText().contains("green")) {
                       JOptionPane.showMessageDialog(console, "green works");
                    }

                    else if (console.getText().contains("red")) {
                        JOptionPane.showMessageDialog(console, "red works");
                    }

                    else if (console.getText().contains("reset")) {
                        JOptionPane.showMessageDialog(console, "reset works");
                    }

                    else {
                        JOptionPane.showMessageDialog(console, "Invalid command, try again");
                    }
            }
    });

    add(console);
}

//private JTextField console = new JTextField(15);


//The default BG colour of the image.

private final static Color BACKGROUND_COL = Color.DARK_GRAY;


 // The underlying image used for drawing. This is required so any previous drawing activity is persistent on the panel.

private BufferedImage image;

/*
 * Draw a line on the image using the given colour.
 * 
 * @param color
 * @param x1
 * @param y1
 * @param x2
 * @param y2
*/

// place pen onto canvas
public void penDown()
{
    penUp = false;
}

//raise pen from canvas
public void penUp()
{
    penUp = true;
}

// turn right from current position
public void turnRight()
{
    switch(direction)
    {
        case UP:
                direction = RIGHT;
                break;
        case DOWN:
                direction = LEFT;
                break;
        case LEFT:
                direction = UP;
                break;
        case RIGHT:
                direction = DOWN;
                break;
        default:
                break;

    }   
}

// turn left from current position
public void turnLeft()
{
    switch(direction)
    {
        case UP:
                direction = LEFT;
                break;
        case DOWN:
                direction = RIGHT;
                break;
        case LEFT:
                direction = DOWN;
                break;
        case RIGHT:
                direction = UP;
                break;
        default:
                break;

    }
}

// draw forward a certain amount
public void forward(int amount)
{

    if(penUp)
        return;

    if (direction == DOWN)
    {
        drawLine(Color.red, xPos, yPos, xPos, yPos + amount );
        yPos = yPos + amount;
    }

    else if (direction == UP)
    {
        drawLine(Color.red, xPos, yPos, xPos, yPos - amount );
        yPos = yPos - amount;
    }

    else if (direction == LEFT)     
    {
        drawLine(Color.red, xPos, yPos, xPos - amount, yPos );
        xPos = xPos - amount;
    }

    else if (direction == RIGHT)        
    {
        drawLine(Color.red, xPos, yPos, xPos + amount, yPos );
        xPos = xPos + amount;
    }

}

// draw backwards a certain amount
public void backward(int amount)
{
    if(penUp)
        return;

    if (direction == DOWN)
    {
        drawLine(Color.red, xPos, yPos, xPos, yPos - amount );
        yPos = yPos - amount;
    }

    else if (direction == UP)
    {
        drawLine(Color.red, xPos, yPos, xPos, yPos + amount );
        yPos = yPos + amount;
    }

    else if (direction == LEFT)     
    {
        drawLine(Color.red, xPos, yPos, xPos + amount, yPos );
        xPos = xPos + amount;
    }

    else if (direction == RIGHT)        
    {
        drawLine(Color.red, xPos, yPos, xPos - amount, yPos );
        xPos = xPos - amount;
    }
}

// change colour to black
public void black()
{
    Graphics g = image.getGraphics();
    g.setColor(Color.black);
}

//change colour to green
public void green()
{
    Graphics g = image.getGraphics();
    g.setColor(Color.green);
}

// change colour to red
public void red()
{
    Graphics g = image.getGraphics();
    g.setColor(Color.red);
}

// draw lines to xy co-ordinates
public void drawLine(Color color, int x1, int y1, int x2, int y2) {

    Graphics g = image.getGraphics();

    g.setColor(color);

    g.drawLine(x1, y1, x2, y2);
}

 //Clears the image contents.

public void clear() {

    Graphics g = image.getGraphics();

    g.setColor(BACKGROUND_COL);

    g.fillRect(0, 0, image.getWidth(),  image.getHeight());
}

@Override
public void paint(Graphics g) {

    // render the image on the panel.
    g.drawImage(image, 0, 0, null);
}

 //Constructor.

}

最佳答案

我可以运行它,但我必须把它拆开然后再装回去。有些事情对我来说没有意义,而且您似乎在没有可用核心的情况下编写了太多代码。

我将文本输入字段从图形面板中分离出来,并创建了一个包含面板 TurtlePanel 来包含这两个面板。我重新设计了颜色逻辑并调整了一些东西。我所做的一些事情只是为了能够独立运行示例代码:

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

import java.awt.image.BufferedImage;

public class TurtlePanel extends JPanel
{
    private GraphicPanel graphics = new GraphicPanel();
    private JTextField console = new JTextField(15);

    public TurtlePanel() {
        add(graphics);
        add(console);

        console.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent arg0) 
            {
                if (console.getText().contains("penup"))
                {
                    graphics.penUp();
                }
                else if (console.getText().contains("pendown"))
                {
                    graphics.penDown();
                }
                else if (console.getText().contains("turnleft"))
                {
                    graphics.turnLeft();
                }
                else if (console.getText().contains("turnright"))
                {
                    graphics.turnRight();
                }
                else if (console.getText().contains("forward"))
                {
                    graphics.forward(50);
                }
                else if (console.getText().contains("backward"))
                {
                    graphics.backward(50);
                }
                else if (console.getText().contains("black"))
                {
                    graphics.black();
                }
                else if (console.getText().contains("green"))
                {
                    graphics.green();
                }
                else if (console.getText().contains("red"))
                {
                    graphics.red();
                }
                else if (console.getText().contains("reset"))
                {
                    graphics.clear();
                }
                else
                {
                    JOptionPane.showMessageDialog(console, "Invalid command, try again");
                }

                console.setText("");
                graphics.repaint();
            }
        });
    }

    public static void main(String[] args) {
        TurtlePanel mainPanel = new TurtlePanel();

        JFrame frame = new JFrame("Simple Testing Frame");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }
}

class GraphicPanel extends JPanel 
{
    private int xPos = 400, yPos = 300;
    private boolean penUp = false;
    private Color color = Color.black;

    private BufferedImage image;
    private final static Color BACKGROUND_COLOR = Color.LIGHT_GRAY;

    private enum Direction {
        UP, DOWN, LEFT, RIGHT
    }

    private Direction direction = Direction.DOWN;

    GraphicPanel() {

        setPreferredSize(new Dimension(800, 600));

        image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);

        setMaximumSize(new Dimension(image.getWidth(), image.getHeight()));

        clear();
    }

    // place pen onto canvas
    public void penDown()
    {
        penUp = false;
    }

    // raise pen from canvas
    public void penUp()
    {
        penUp = true;
    }

    // turn right from current position
    public void turnRight()
    {
        switch (direction)
        {
            case UP:
                direction = Direction.RIGHT;
                break;
            case RIGHT:
                direction = Direction.DOWN;
                break;
            case DOWN:
                direction = Direction.LEFT;
                break;
            case LEFT:
                direction = Direction.UP;
                break;
        }
    }

    // turn left from current position
    public void turnLeft()
    {
        switch (direction)
        {
            case UP:
                direction = Direction.LEFT;
                break;
            case LEFT:
                direction = Direction.DOWN;
                break;
            case DOWN:
                direction = Direction.RIGHT;
                break;
            case RIGHT:
                direction = Direction.UP;
                break;
        }
    }

    // draw forward a certain amount
    public void forward(int amount)
    {
        if (penUp)
        {
            return;
        }

        switch (direction)
        {
            case UP:
                drawLine(xPos, yPos, xPos, yPos - amount );
                yPos = yPos - amount;
                break;
            case DOWN:
                drawLine(xPos, yPos, xPos, yPos + amount );
                yPos = yPos + amount;
                break;
            case LEFT:
                drawLine(xPos, yPos, xPos - amount, yPos );
                xPos = xPos - amount;
                break;
            case RIGHT:
                drawLine(xPos, yPos, xPos + amount, yPos );
                xPos = xPos + amount;
                break;
        }
    }

    // draw backwards a certain amount
    public void backward(int amount)
    {
        if (penUp)
        {
            return;
        }

        switch (direction)
        {
            case UP:
                drawLine(xPos, yPos, xPos, yPos + amount );
                yPos = yPos + amount;
            case DOWN:
                drawLine(xPos, yPos, xPos, yPos - amount );
                yPos = yPos - amount;
                break;
            case LEFT:
                drawLine(xPos, yPos, xPos + amount, yPos );
                xPos = xPos + amount;
            case RIGHT:
                drawLine(xPos, yPos, xPos - amount, yPos );
                xPos = xPos - amount;
                break;
        }
    }

    // change colour to black
    public void black()
    {
        color = Color.black;
    }

    // change colour to green
    public void green()
    {
        color = Color.green;
    }

    // change colour to red
    public void red()
    {
        color = Color.red;
    }

    // draw lines to xy co-ordinates
    public void drawLine(int x1, int y1, int x2, int y2) {

        Graphics g = image.getGraphics();

        g.setColor(color);
        g.drawLine(x1, y1, x2, y2);
    }

    // Clears the image contents.
    public void clear() {

        Graphics g = image.getGraphics();

        g.setColor(BACKGROUND_COLOR);
        g.fillRect(0, 0, image.getWidth(), image.getHeight());
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        // render the image on the panel.
        g.drawImage(image, 0, 0, null);
    }
}

enter image description here

关于Java turtle 图形用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43761606/

相关文章:

java - 如何在 Java 中旋转屏幕组件?

java - 如何编写一个按键监听器来跟踪 Java 中的所有击键?

java - 每行列数不同的 JTable

java - JTable 不会在 fireTableChanged 上刷新

java - 如何在面板内创建网格(带有网格线),并让鼠标监听器在单击任何网格单元格时给出相对于面板的坐标?

java - 无法在 java.awt.BufferdImage/Graphics2D 中获得正确的文本高度

java - 如何从圆列表中选择圆以从 JFrame 中删除?

java - 变量取消引用错误没有解决

java - 如何终止 View 作用域 bean 中的线程?

java - 在耶拿阅读嵌套的 RDF 三元组