The title says it all.
I have a class which extends JPanel
. The size of the JPanel is set by adding the below method in the class:
@Override
public Dimension getPreferredSize() {
return new Dimension(WIDTH, HEIGHT);
}
the relevant fields of this class are:
int position = 0;
int randomSize = 0;
int randomPositionX = 0;
int randomPositionY = 0;
public final static int MAX_SIZE = 100;
public final static int MIN_SIZE = 10;
public final static int WIDTH = 500;
public final static int HEIGHT = 500;
private Random rand = new Random();
String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
I choose a random size (Maximum of 100 and minimum of 10) and a random coordinate from a method. I also choose a random index for the string alphabets
:
randomSize = MIN_SIZE + (rand.nextInt(MAX_SIZE - MIN_SIZE) + 1);
randomPositionX = rand.nextInt(WIDTH - randomSize);
randomPositionY = rand.nextInt(HEIGHT - randomSize);
position = rand.nextInt(alphabets.length());
My attempt at drawing the alphabet and circle:
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(randomPositionX, randomPositionY, randomSize, randomSize);
g.setFont(new Font("TimesRoman", Font.PLAIN, randomSize));
g.setColor(Color.RED);
g.drawString(alphabets.charAt(position) + "", randomPositionX + (randomSize/2), randomPositionY + (randomSize/2));
}
But it doesn't draw the alphabet at the center of the circle. In short, the problematic line is
g.drawString(alphabets.charAt(position) + "", randomPositionX + (randomSize/2), randomPositionY + (randomSize/2));
How do I achieve what I want?
Aucun commentaire:
Enregistrer un commentaire