Java GUI: repaint () или проблема взаимодействия с классом - PullRequest
0 голосов
/ 07 мая 2018

Итак, я создаю графический проект с черепахой, и у меня возникают проблемы с перемещением черепахи при вводе команды. Ниже приведены два взаимодействующих класса: мой класс TextPanel, который обрабатывает пользовательский ввод, и GraphicsPanel, который содержит «холст», пригодный для рисования и т. Д.

Поскольку в данный момент я не получаю никаких ошибок, мне интересно, правильно ли я вызываю класс GraphicsPanel или я использую repaint (), и это неправильный метод? Я в растерянности и могу использовать свежую пару глаз. Спасибо за ваше время.

public class TextPanel extends JPanel implements ActionListener {

private JTextArea textArea;
private JScrollPane scrollPane;
private JTextField commField;
private JButton enterBut;
private TextListener textListener;
private GraphicsPanel graphicsPanel;

//***********//
//CONSTRUCTOR//
//***********//

public TextPanel() {

    textArea = new JTextArea();
    scrollPane = new JScrollPane ( textArea );
    enterBut = new JButton("Execute");
    commField = new JTextField(10);
    graphicsPanel = new GraphicsPanel();


    textArea.setLineWrap(true);         //stops text from going outside
    textArea.setWrapStyleWord(true);    //panel boundaries

    //**********************//
    //COMMAND IMPLEMENTATION//
    //**********************//

    commField.addActionListener(new ActionListener() {


        public void actionPerformed(ActionEvent e) {

            if(commField.getText().contains("penup")) {
                GraphicsPanel.penUp();
            }
            else if(commField.getText().contains("pendown")) {
                GraphicsPanel.penDown();
            }
            else if(commField.getText().contains("turnright")) {
                GraphicsPanel.turnRight();
            }
            else if(commField.getText().contains("turnleft")) {
                GraphicsPanel.turnLeft();
            }
            else if(commField.getText().startsWith("forward")) {        //getText method retrives user input from JTextField
                String cForward = commField.getText();                  //<startsWith> searches string for desired command
                String[] cForwardArray = cForward.split("\\s+");        //string array created and split with " " as split
                try {
                    int distance = Integer.parseInt(cForwardArray[1]);  //parseInt takes the integer from string split
                    GraphicsPanel.forward(distance);                    //GraphicsPanel command called + distance integer
                    textArea.append(cForward + "\n");           //test for variable values
                    GraphicsPanel.validate();
                    GraphicsPanel.repaint();                            //canvas is repainted 


                } 
                catch (Exception ev) {
                    JOptionPane.showMessageDialog(textArea, 
                            "Invaild or missing parameter, check the help section\n"
                            + "for more information on Commands");
                }
            }
            else if(commField.getText().startsWith("backward")) {
                String cBackward = commField.getText();
                String[] cBackwardArray = cBackward.split("\\s+");
                try {
                    int distance = Integer.parseInt(cBackwardArray[1]);
                    GraphicsPanel.backward(distance);
                    textArea.append(cBackward +"\n");
                    GraphicsPanel.repaint();
                } 
                catch (Exception ev) {
                    JOptionPane.showMessageDialog(textArea, 
                            "Invaild or missing parameter, check the help section\n"
                            + "for more information on Commands");
                }
            }

            else if(commField.getText().contains("black")) {
                GraphicsPanel.black(Color.black);
            }
            else if(commField.getText().contains("green")) {
                GraphicsPanel.green(Color.green);
            }
            else if(commField.getText().contains("red")) {
                GraphicsPanel.red(Color.red);
            }
            else if(commField.getText().contains("reset")) {
                GraphicsPanel.clear();
            }
            else {
                JOptionPane.showMessageDialog(textArea, "Invalid command, try again");
            }

            commField.setText("");
            GraphicsPanel.repaint();


        }
    });


    //****************//
    //PANEL DIMENSIONS//
    //****************//

    setBackground(Color.black);

    Dimension dim = getPreferredSize();     //sets dimensions of panel
    dim.width = 250;
    setPreferredSize(dim);

    //setBorder(BorderFactory.createTitledBorder("Enter Commands here: "));
    //setTitleColor(Color.white); //not sure why this doesnt change the text colour


    //**************//
    //GRIDBAG LAYOUT//
    //**************//

    setLayout(new GridBagLayout());
    GridBagConstraints constraint = new GridBagConstraints();

    add(commField, constraint);

    constraint.fill = GridBagConstraints.HORIZONTAL;
    constraint.ipady = 20;
    constraint.ipadx = 60;
    constraint.insets = new Insets(10, 5, 0, 0);
    constraint.weightx = 1;
    constraint.weighty = 0;
    constraint.gridx = 0;                           //grid position
    constraint.gridy = 0;

    add(commField, constraint);
    //***********************//

    constraint.fill = GridBagConstraints.HORIZONTAL;
    constraint.ipady = 15;
    constraint.ipadx = 25;
    constraint.anchor = GridBagConstraints.PAGE_END;    //anchors to bottom of GUI
    constraint.insets = new Insets(10, 0, 0, 0);        //inserts gap
    constraint.weightx = 0;
    constraint.weighty = 0;
    constraint.gridx = 1;                       
    constraint.gridy = 0;

    add(enterBut, constraint);

    //*************************//

    constraint.fill = GridBagConstraints.BOTH;      //option how to fill 'cell' 
    constraint.ipady = 150;                         //dim of component 
    constraint.ipadx = 150;
    constraint.insets = new Insets(0, 5, 0, 0);
    constraint.gridwidth = 3;                       //how many grid cell it spans
    constraint.weightx = 1;                         //precedent for space
    constraint.weighty = 1;
    constraint.gridx = 0;                           //grid position
    constraint.gridy = 1;

    add(new JScrollPane(textArea), constraint);                     //adds component
                                                                    //and JSCrollPane
    //************************//

    //**NOTES****************************//
    //next time use smaller variable name//
    //***********************************//

}


private void setTitleColor(Color white) {


}

public void appendText(String text) {

}


@Override
public void actionPerformed(ActionEvent e) {


}

public void setTextListener(textListener listener) {
    this.TextListener = listener;
}
}

Это мой класс GraphicsPanel, содержащий командные функции и настройки JPanel, включая bufferedimage и т. Д.

@SuppressWarnings("serial")                     //Represents the graphics display panel
                                                //panel within the turtle program. 
public class GraphicsPanel extends JPanel {     //This panel contains an image which 
                                                //is updated to reflect user commands.



//background colour image



private final static Color BACKGROUND_COL = Color.DARK_GRAY;
private final static int TURTLE_X_SIZE = 20, TURTLE_Y_SIZE = 20;

private TextPanel TextPanel;
//private JTextField getTextField();

private BufferedImage image, turtleDisplay;     //The underlying image used 
                                                //for drawing. This is required


//Djm added
private Color PenColour = Color.GREEN;          //so any previous drawing activity is 
private boolean penDown = false;                //is persistent on the panel.
private int xPos=325, yPos=180;
private int direction = 180;                    //robot pointing down the screen;




//change drawLine colour

public void black(Color color) {
    color = Color.black;
}

public void green(Color color) {
    color = Color.green;
}

public void red(Color color) {
    color = Color.red;
}

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);
}


public void penDown() {
    penDown = true;
}

//***********************************//

public void penUp() {
    penDown = false;
}

//***********************************//

public void turnRight() {
    direction +=90;
    if (direction >= 360)
        direction = 0;
}

//***********************************//

public void turnLeft() {
    direction -=90;
    if (direction < 0)
        direction = 270;
}

//***********************************//


//sends the turtle forward

public void forward(int distance) {
                                    //Graphics g = image.getGraphics();
    int x=xPos,y=yPos;
                                    //stored xPos and yPos are current location

    if (direction == 0) {           //robot facing up the screen, so forward subtracts y
        y = yPos-distance;
    }
    else if (direction == 90) {     //robot facing right so forward add x
        x = xPos + distance;
    }
    else if (direction == 180) {     //robot facing down the screen, so forwards adds to y
        y = yPos + distance;
    }
    else if (direction == 270) {    //robot facing left, so forwards subtracts from x
        x = xPos - distance;
    }
    else {
        System.out.println("strange, shouldn't get here");
    }
    if (penDown) {
                                            //x=400; y=400;
        drawLine(PenColour, xPos, yPos, x, y);
                                            //g.drawLine(xPos,yPos,x,y);
    }
                                            //now robot has moved to the new position
    xPos = x;
    yPos = y;
}

//***********************************//

//sends the turtle backwards

public void backward(int distance) {

    int x=xPos,y=yPos;
    //stored xPos and yPos are current location

    if (direction == 0) {           //robot facing up the screen, so forward adds y
        y = yPos + distance;
    }
    else if (direction == 90) {     //robot facing right so forward subtract x
        x = xPos - distance;
    }
    else if (direction == 180) {     //robot facing down the screen, so forwards subtracts to y
        y = yPos - distance;
    }
    else if (direction == 270) {    //robot facing left, so forwards adds from x
        x = xPos + distance;
    }
    else {
        System.out.println("strange, shouldn't get here");
    }
    if (penDown) {
                                                            //x=400; y=400;
        drawLine(PenColour, xPos, yPos, x, y);
                                                            //g.drawLine(xPos,yPos,x,y);
    }
                                                            //now robot has moved to the new position
    xPos = x;
    yPos = y;

}

//***********************************//

 //Clears the image contents.

public void clear() {

    Graphics g = image.getGraphics();
    g.setColor(BACKGROUND_COL);
    g.fillRect(0, 0, image.getWidth(),  image.getHeight());
}

//***********************************//


public void setTurtleColour(Color col) {
    Graphics g = turtleDisplay.getGraphics();
    g.setColor(col);
    g.fillRect(0, 0, turtleDisplay.getWidth(),  turtleDisplay.getHeight());
}

@Override
public void paintComponent(Graphics g) 
{


    super.paintComponent(g);

    // render the image on the panel.
    g.drawImage(image, 0, 0, null);
    g.drawImage(turtleDisplay, xPos-TURTLE_X_SIZE/2, yPos-TURTLE_Y_SIZE/2, null);

}



//***********//
//CONSTRUCTOR//
//***********//

public GraphicsPanel() {

    //main drawing area
    image = new BufferedImage(650, 400, BufferedImage.TYPE_INT_RGB);


    //small image to display on top of drawing area to represent the turtle
    turtleDisplay =  new BufferedImage(20, 20, BufferedImage.TYPE_INT_RGB);

    //set up turtle
    setTurtleColour(PenColour);

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

    clear();
}

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...