Code:
Random rand = new Random();
JPanel mainPanel;
int randomSize = 0;
int randomPositionX = 0;
int randomPositionY = 0;
final static int FRAME_HEIGHT = 500;
final static int FRAME_WIDTH = 500;
final static int TITLE_BAR = 30 ;
final static int MAX_SIZE = 100;
final static int MIN_SIZE = 10 ;
/* All the below code is put into a method */
mainPanel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(randomPositionY, randomPositionX, randomSize, randomSize);
}
};
do{
randomSize = rand.nextInt(MAX_SIZE) + 1;
}while(randomSize < MIN_SIZE);
do{
randomPositionX = rand.nextInt(FRAME_WIDTH);
randomPositionY = rand.nextInt(FRAME_HEIGHT);
}while((randomPositionX + randomSize > FRAME_WIDTH) || (randomPositionY + randomSize > FRAME_HEIGHT - TITLE_BAR));
repaint();
What I want is the circle to have a random size such that it should have a minimum size of 10 and a maximum size of 100. The circle should also be painted in a random coordinate such that the circle is fully visible inside the JPanel mainPanel
.
Note that mainPanel
will be added to a JFrame whose size is set using setSize(FRAME_WIDTH, FRAME_HEIGHT);
.
But the problem is that sometimes, a part of the circle is half outside and half inside the JPanel:
Where did I go wrong?
Aucun commentaire:
Enregistrer un commentaire