【发布时间】:2015-07-03 05:43:17
【问题描述】:
代码:
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();
我想要的是具有随机大小的圆,使其最小大小为 10,最大大小为 100。圆还应该以随机坐标绘制,以使圆完全在 JPanel mainPanel 中可见。
请注意,mainPanel 将添加到使用 setSize(FRAME_WIDTH, FRAME_HEIGHT); 设置大小的 JFrame。
但问题是,有时,圆圈的一部分在JPanel的外面一半在里面:
我哪里做错了?
【问题讨论】:
标签: java swing random paintcomponent