I have this inner class:
private class Plats extends JComponent{
private String namn;
Plats(int x, int y, String n){
namn=n;
setBounds(x-10, y-10, 150, 40);
setPreferredSize(new Dimension(20, 20));
setMinimumSize(new Dimension(20, 20));
setMaximumSize(new Dimension(20, 20));
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillOval(0, 0, 20, 20);
g.setColor(Color.BLACK);
g.setFont(font);
g.drawString(namn, 0, 34);
}
public boolean contains(int x, int y){
return x<20 && x>0 && y<20 && y>0;
}
}
I want to set the bounds of the component to the width of the string that the constructor gets, but I can only get it to work if I do it inside the paintComponent method since I need the graphics object. It feels wrong to do it in the paintComponent method since every time the component has to be repainted it will set the bounds again and I only want to do it once when it is created.
Suggestions how I can solve this? Or should I just do it in the paintComponent anyway?, it works but I doesnt feel like a nice solution :( ?