Java在框架上移动正方形-如何在框架边缘停止?

Java在框架上移动正方形-如何在框架边缘停止?,java,graphics,shapes,Java,Graphics,Shapes,我有一个用键盘移动方块的程序。当我按下其中一个箭头键时,它可以很好地移动,但是如果我将它移动到帧的边缘,我希望它停止。然而,它并没有做到这一点。如果我把方块移到画面的边缘,它会继续移动,并正好越过屏幕的边缘 我在我的代码中加入了一些控件,试图阻止方块,但它们似乎不起作用。我不太确定这里出了什么问题 这是设置和绘制正方形的代码: import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geo

我有一个用键盘移动方块的程序。当我按下其中一个箭头键时,它可以很好地移动,但是如果我将它移动到帧的边缘,我希望它停止。然而,它并没有做到这一点。如果我把方块移到画面的边缘,它会继续移动,并正好越过屏幕的边缘

我在我的代码中加入了一些控件,试图阻止方块,但它们似乎不起作用。我不太确定这里出了什么问题

这是设置和绘制正方形的代码:

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

@SuppressWarnings("serial")
public class MovingSquare extends JPanel implements ActionListener, KeyListener
{
    // We need a timer to move the shape
    Timer shapeTimer = new Timer(5, this);

    // X and Y coordinates of square (top left corner), and the factors by which it will move or resize each time
    double xPos = 0, yPos = 0, movementX = 0, movementY = 0;

    // Size of the square
    int squareSize = 40;

    // Width and height of the parent frame
    int windowWidth;
    int windowHeight;

    // Movement bounds of the square
    // These will prevent it from being moved off the edge of the frame
    int xBound;
    int yBound;

    // Constructor method for our class
    public MovingSquare(int w, int h)   // Constructor is passed the size of the parent frame
    {
        // Start the timer
        shapeTimer.start();

        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);

        windowWidth = w;
        windowHeight = h;

        xBound = (windowWidth - squareSize);
        yBound = (windowHeight - squareSize);
    }

    // This is where the fun starts!  Painting the graphics object
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;

        // Create a new rectangle (which is actually a square!)
        Rectangle2D movableSquare = new Rectangle2D.Double(xPos, yPos, squareSize, squareSize);

        // Draw the above square on the graphics object
        g2.draw(movableSquare);
    }

    public void actionPerformed(ActionEvent e) 
    {
        // Redraw the square when something happens
        repaint();

        // Set the new x and y coordinates, depending on which direction we have moved
        xPos += movementX;
        yPos += movementY;
    }

    public void moveUp() 
    {
        // Check to see if the shape is already at the top edge of the screen
        if (yPos == 0) 
        {
            movementY = 0;
            movementX = 0;
        }

        // Set the movement factor - negative Y because we are moving UP!
        movementY = -0.5;
        movementX = 0;
    }

    public void moveDown() 
    {
        // Check to see if the shape is already at the bottom edge of the screen - specified by the X and Y bounds
        if (yPos == yBound) 
        {
            movementY = 0;
            movementX = 0;              
        }

        // Set the movement factor - positive Y because we are moving DOWN!
        movementY = 0.5;
        movementX = 0;
    }

    public void moveLeft()
    {
        // Check to see if the shape is already at the left hand edge of the screen         
        if (xPos == 0) 
        {
            movementY = 0;
            movementX = 0;              
        }

        // Set the movement factor - negative X because we are moving LEFT!         
        movementX = -0.5;
        movementY = 0;
    }

    public void moveRight() 
    {
        // Check to see if the shape is already at the right hand edge of the screen - specified by the X and Y bounds
        if (xPos == xBound)
        {
            movementY = 0;
            movementX = 0;
        }

        // Set the movement factor - positive X because we are moving RIGHT!            
        movementX = 0.5;
        movementY = 0;
    }

    public void enlargeSquare() 
    {
        // Make the square larger
        squareSize++;
    }

    public void shrinkSquare() 
    {
        // Make the square smaller
        squareSize--;
    }

    public void keyPressed(KeyEvent e) 
    {
        // Get the Key Code of the key that has been pressed
        int keyCode = e.getKeyCode();

        // If the up key has been pressed
        if (keyCode == KeyEvent.VK_UP) 
        {
            // Move shape up
            moveUp();
        }

        // If the down key has been pressed
        if (keyCode == KeyEvent.VK_DOWN) 
        {
            // Move shape down
            moveDown();
        }

        // If the right key is pressed
        if (keyCode == KeyEvent.VK_RIGHT)
        {
            // Move shape right
            moveRight();
        }

        // If the left key is pressed
        if (keyCode == KeyEvent.VK_LEFT) 
        {
            // Move shape left
            moveLeft();
        }

        // If the left brace key is pressed
        if (keyCode == KeyEvent.VK_OPEN_BRACKET)
        {
            shrinkSquare();
        }

        // If the right brace key is pressed
        if (keyCode == KeyEvent.VK_CLOSE_BRACKET)
        {
            enlargeSquare();
        }
    }

    public void keyTyped(KeyEvent e) 
    {

    }

    public void keyReleased(KeyEvent e)
    {
        // Get the Key Code of the key that has been released
        int keyCode = e.getKeyCode();

        // If the down key was released
        if (keyCode == KeyEvent.VK_UP) 
        {
            movementX = 0;
            movementY = 0;
        }

        // If the down key was released
        if (keyCode == KeyEvent.VK_DOWN) 
        {
            movementX = 0;
            movementY = 0;
        }

        // If the right key was released
        if (keyCode == KeyEvent.VK_RIGHT) 
        {
            movementX = 0;
            movementY = 0;
        }

        // If the left key was released
        if (keyCode == KeyEvent.VK_UP) 
        {
            movementX = 0;
            movementY = 0;
        }               
    }   
}
这是主要课程:

import javax.swing.JFrame;

public class Square 
{

public static void main(String args[]) 
{
    // Set width and height of frame
    int frameWidth = 1024;
    int frameHeight = 768;

    // Create new frame and set size
    JFrame frmMain = new JFrame();
    frmMain.setSize(frameWidth, frameHeight);

    // Create a moving square and add to the frame
    MovingSquare mySquare = new MovingSquare(frameWidth, frameHeight);      
    frmMain.add(mySquare);

    // Final configuration settings for frame.
    frmMain.setVisible(true);
    frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmMain.setTitle("Moving Square");
}

}
你的方法是更新正方形的位置,远远超过你的moveXxx方法,你应该在那里进行范围检查

@Override
public void actionPerformed(ActionEvent e) 
{
    // Set the new x and y coordinates, depending on which direction we have moved
    xPos += movementX;
    yPos += movementY;

    if (xPos < 0) {
        xPos = 0;
    } else if (xPos + squareSize > xBound) {
        xPos = xBound - squareSize;
    }
    if (yPos < 0) {
        yPos = 0;
    } else if (yPos + squareSize > yBound) {
        yPos = yBound - squareSize;
    }

    // Redraw the square when something happens
    repaint();
}

如果你知道屏幕和矩形的宽度和高度,你可以很容易地检查它是否在里面:

int fX0 = 0, // left x border
    fX1 = frameWidth, // right x border
    fY0 = 0, // top y border
    fY1 = frameHeight; // bottom y border
int rX0, rX1, rY0, rY1; // keep these values updated width the rectangles position:
    //rX0 = rectangle position x
    //rX1 = rectangle position x + rectangle width
    //rY0 = rectangle position y
    //rY1 = rectangle position y + rectangle height
// Then, to check if the rect is inside the frame:
if (
    rX0 >= fX0 &&
    rX1 <  fX1 &&
    rY0 >= fY0 &&
    rY1 <  fY1
) { /* the rectangle is inside the frame bounds */ }
else { /* it's not inside the bounds, e.g. cancel movement */ }

您可以制作一个额外的方法:

public boolean Check(){
 if(xPos >0 && xPos-squareSize<frameWidth && yPos>0 && yPos-squareSize<frameHeight){
    //use a flag for example and make it false
  }else
     //flag==true 

   return flag;
 }

好的,这似乎起作用了!如果你不是天才的话,你肯定是个专家-
public boolean Check(){
 if(xPos >0 && xPos-squareSize<frameWidth && yPos>0 && yPos-squareSize<frameHeight){
    //use a flag for example and make it false
  }else
     //flag==true 

   return flag;
 }
public void KeyPressed(KeyEvent key){

 if(Check()==true){
  ..........//the code you have into KeyPressed method
  }


}//end of method KeyPressed