Search code examples
javaswingjpanelpaintcomponent

How do I draw text in my Java GUI based on an if condition in my paintComponent?


I have an if condition to win a game in my paintComponent and I was wondering how should I draw it to display in my Jpanel Java GUI?

 @Override
    public void paintComponent (Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        Graphics2D buffer = world.createGraphics();
        buffer.setColor(Color.black);
        buffer.fillRect(0, 0, GameConstants.WORLD_WIDTH, GameConstants.WORLD_HEIGHT);

        this.p1.drawImage(buffer);
        this.p2.drawImage(buffer);
        this.p3.drawImage(buffer);
        this.p4.drawImage(buffer);
        this.s1.drawImage(buffer);
        this.a1.drawImage(buffer);
        this.a2.drawImage(buffer);
        this.a3.drawImage(buffer);
        this.a4.drawImage(buffer);
        //g2.drawImage(this.Background,0,0,null);
        g2.drawImage(world,0,0,null);
        if (this.p1.x == 6000 && this.p2.x == 6000 && this.p3.x == 6000 && this.p4.x == 6000){
            g2.drawString("YOU WIN!!!");
        }


    }

Solution

  • To draw a String you must specify the coordinates.

    g.setFont();  // set a font if you wish use -- new Font(...)
    if (some condition) {
        g.drawString(str, x, y);
    }
    

    But it appears you are doing a number of things incorrectly. First, you should put super.paintComponent(g); as your first statement in the paintComponent method. And you should only be painting using the graphics context supplied by paintComponent Also note that

    1. the coordinates must be within the bounds of the container where you are drawing, and
    2. you must set the color using g.setColor() where the argument is from the Color class. Otherwise you are probably painting in the same default color of the container's background, so it won't be seen.

    You mays also want to consider using JOptionPane to display a winning message or any other of a variety of messages. Also check out the Java Tutorials on examples of painting and using JOptionPane.