How to use "drawRect" to draw on a component?

Asked

Viewed 496 times

1

I am learning Graphics, but I can’t make a square:

public static void main(String[] args)
{   
    JFrame tela = new JFrame("Snake");

    tela.setSize(500, 500);
    tela.setVisible(true);  

    Graphics g = tela.getGraphics();

    g.drawRect(5, 5, 50, 50);
}

What’s the matter?

1 answer

1


The problem is that if you need to change the way a component is being designed, you need to reset the method paintComponent.

getGraphics will return you an object Graphics where, any change made (for example, draw the square) will be temporary and you will lose it at the first moment that the Swing determines that the component should be repainted.

So, one way to do this without inheritance - already answered by Thiago Luiz - is to overwrite the method paintComponent of a JComponent or JPanel and then do all the painting work in that method, using the object Graphics received as argument. Then you can add the created component to your JFrame.

import java.awt.Graphics;
import javax.swing.*;

public class Main {

    public static void main(String[] args) {    
        JFrame tela = new JFrame("Snake");
        tela.setSize(500, 500);
        tela.setVisible(true); 

        JPanel painelComQuadrado = new JPanel(){
            // Sobrescrevendo o método 'paintComponent' do 'JPanel'.
            @Override public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawRect(5, 5, 50, 50);
            }
        };
        tela.add(painelComQuadrado);

        // Chamando 'revalidate' e 'repaint' porque o painel com o
        // quadrado foi inserido no JFrame após o 'setVisible'.
        tela.revalidate();
        tela.repaint();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.