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();
}
}