Drzrgrf
Drzrgrf

Reputation: 3

JAVA How can I update an already drawn string?

I am trying to repaint a string used to keep score in a small java game I'm making but I am not sure how to have the string change on the screen. As you can see it is initially drawn, and I am trying to update it inside of the ingame if statement.

public void paint(Graphics g)
    {
        super.paint(g);

        g.setColor(Color.white);
        g.fillRect(0, 0, d.width, d.height);
        //g.fillOval(x,y,r,r);

        //Draw Player
        g.setColor(Color.red);
        g.fillRect(p.x, p.y, 20, 20);
        if(p.moveUp == true) {
            p.y -= p.speed;
        }
        moveObstacles();
        for (int i = 0; i < o.length; i++ ) {
            g.fillRect(o[i].x, o[i].y, 10, 5);
        }

        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = this.getFontMetrics(small);
        g.setColor(Color.black);
        g.setFont(small);
        g.drawString(message, 10, d.height-60);
        g.drawString(message2, 10, d.height-80);

        if (ingame) {
            for (int i = 0; i < o.length; i++ ) {
                if ((o[i].x < p.x + 20 && o[i].x > p.x) && (o[i].y < p.y + 20 && o[i].y > p.y)) {
                    p.x = BOARD_WIDTH/2;
                    p.y = BOARD_HEIGHT - 60;
                    lives = lives - 1;
                    g.drawString(message, 10, d.height-60); 
                }
            }
            // g.drawImage(img,0,0,200,200 ,null);
        }
        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }

Upvotes: 0

Views: 187

Answers (1)

camickr
camickr

Reputation: 324157

You create a method like setMessage(…). This method with then save the "message" as a property in your class.

The method will then invoke repaint(), which will cause the component to repaint itself.

This is how all Swing components work. Think about a JLabel and the setText(…) method.

Also:

  1. Custom painting is done by overriding the paintComponent() method, not the paint() method.

  2. There is no need for the Toolkit sync() method.

  3. You should NOT dispose of the Graphics object.

Upvotes: 1

Related Questions