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

1

I'm learning Graphics , but I can not 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 problem?

    
asked by anonymous 03.09.2015 / 16:40

1 answer

1

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

getGraphics will return you a Graphics object where any changes made (for example, drawing the square) will be temporary and you will lose it at the first moment 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 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();
    }
}
    
03.09.2015 / 20:57