My drawString won't work
Im somewhat new in java, been programming for about a year now and im currently working on a project that lets the user choose a map (worldmap for example) and add cities to that map by clicking the map.
When the user clicks on the map he/she inputs a name and the city is drawn on those coordinates, and that work's fine. My problem is that I also want the name of the city to be drawn above the city, but I can't get it to work for some reason. It should be an easy task, but been trying for several hours now and it's starting to get very annoying so I hope someone else can help me with this simple enquiry.
The code:
public cla开发者_Python百科ss Rita extends JComponent{
private boolean klickad=false;
protected int xx=0;
private int yy=0;
public Rita(int x, int y){
xx=x;
yy=y;
setBounds(x, y, 20, 20);
setPreferredSize(new Dimension(20,20));
setMaximumSize(new Dimension(20,20));
setMinimumSize(new Dimension(20,20));
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
drawString(g, xx+5, yy);
if(klickad==false)
klickadVal(g, xx, yy);
else if(klickad==true)
oKlickadVal(g);
}
public void drawString(Graphics g, int x, int y){
setFont(new Font("Courier New", Font.PLAIN, 16));
g.setColor(Color.BLACK);
g.drawString("Test test test test test", x, y);
}
public void klickadVal(Graphics g, int x, int y){
g.setColor(Color.RED);
g.fillRect(0,0,getWidth(),getHeight());
}
public void oKlickadVal(Graphics g){
g.setColor(Color.BLUE);
g.fillRect(0, 0, getWidth(),getHeight());
Thanks in advance /Jimmy
It's because of your drawing coordinates should be define relative to the component.
You are setting the bounds of the component to x,y,w,h
and drawing your text to the same x
and y
.
If x > w
or y > h
, then it won't be visible.
Change your code to this, using relative coordinates for the drawing commands:
protected void paintComponent(Graphics g){
super.paintComponent(g);
drawString(g, 5, 10);
if(klickad==false)
klickadVal(g, 0, 0);
else if(klickad==true)
oKlickadVal(g);
}
And be aware of that your drawing area is only 20px*20px, because of your bounds width and height.
You are calling klickadVal or oKlickadVal after you've painted the string. These two methods fill the entire component with a single color overwriting the string you've displayed.
精彩评论