简体   繁体   中英

How do I make sure that my image won't be drawn outside my JFrame?

I am working on a project where a 64x64 red ball is randomly drawn in a 600x600 window and it will move and bounce off of the "walls". (Borders of the window) My red ball is a JLabel that is being drawn on a JPanel. I am using setBounds. I believe the numbers you enter in setBounds will be the upper left corner of the image you are drawing. So I figured that the random coordinates of the image should be 0 to 536 (Which is 600 - 64). However, when I do that, the only half of the image is shown. The other half can't be seen because it is outside of the JFrame. How can I make it where it will always be 100% visible when run?

import java.awt.*;

import javax.swing.*;

public class BallBounce {

public JFrame frame;
public JPanel panel;
public JLabel ball;
public ImageIcon ballIcon = new ImageIcon("images/ball.png");
public int bpx; //ballpositionx
public int bpy;
public int bsx = 1; //ballspeedx
public int bsy = 1;

public BallBounce() {
    frame = new JFrame();
    frame.setTitle("Ball Bounce");
    frame.setSize(600, 600);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setVisible(true);

    panel = new JPanel();
    panel.setLayout(null);
    panel.setSize(600,600);

    ball = new JLabel();
    ball.setIcon(ballIcon);
    bpx = (int)(Math.random()*536)+0;
    bpy = (int)(Math.random()*536)+0;
    ball.setBounds(bpx, bpy, 64, 64);
    panel.add(ball);

    frame.add(panel);
    frame.revalidate();
}

public static void main(String args[]) {
    BallBounce bb = new BallBounce();
}

}

由于球的中心线实际上位于球的中间-通过将半径添加到设定边界来补偿差异-只是一个快速答案

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM