public class TerrisView extends JFrame {
public Canvas canvas;
public TerrisView(String title) {
super(title);
canvas = new Canvas();
canvas.setSize(300, 400);
canvas.setBackground(Color.WHITE);
// setSize(300, 400);
this.add(canvas, BorderLayout.CENTER);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
paint();
}
public void paint() {
// this.createBufferStrategy(2);
// Graphics gp=getBufferStrategy().getDrawGraphics();
// gp.setColor(Color.RED);
// gp.fillRect(100, 100, 50, 50);
// getBufferStrategy().show();
Graphics gp = canvas.getGraphics();
gp.setColor(Color.BLACK);
gp.fillRect(0, 0, 10, 10);
}
}
Why does it fail to draw the Rect on the canvas? What is wrong with the code?
JComponentinstead ofCanvaspaintComponent(Graphics)instead ofpaint(Graphics)Before I formatted that code, I failed to notice that
paint()was not an override, and this classic..Don’t do that with components. Use the
Graphicsobject that is passed to the methods mentioned in point 2, and paint when told to do so.This answer is already accepted, but I could not resist reviewing and cleaning up the source to make an SSCCE, as well as add a few more tweaks. See comments in code for further tips.