I am having issues with my Applet not painting the required graphics.
For some reason, it updates the coloring in the graphics, as you can see this when it prints, it recognizes the mouse is being moved, the graphics are not null, but it still refuses to paint.
How can this be fixed?
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JApplet;
public class GameApplet extends JApplet implements MouseListener, MouseMotionListener{
/**
*
*/
private static final long serialVersionUID = -6796451079056583597L;
Graphics2D g;
Image image;
Point p = new Point(-100, -100);
public void init(){
init(1000, 900);
}
public void init(int x, int y){
setSize(x, y);
image = createImage(x, y);
g = (Graphics2D) image.getGraphics();
//if(Graphic.setGraphic(image.getGraphics())){
if(g != null)
System.out.println("Graphics made");
//}
g.setColor(Color.GREEN);
g.fillRect(0, 0, x, y);
System.out.println(g+", "+ (g != null));
addMouseListener(this);
addMouseMotionListener(this);
//Graphic.paint();
setVisible(true);
}
@Override
public void paint(Graphics g){
g.setColor(Color.red);
g.fillRect(0, 0, 500, 500);
}
public void update(Graphics g){
paint(g);
}
@Override
public Graphics getGraphics(){
return g;
}
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e);
}
@Override
public void mousePressed(MouseEvent e) {
p = e.getPoint();
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
showStatus(e.toString());
g.fillOval(e.getPoint().x - 5, e.getPoint().y - 5, 10, 10);
p = e.getPoint();
repaint();
}
}
The "don't paint in top-level containers" still needs attending to, but it was not the immediate source(s) of the problem. Try this simpler code.
As per my recommendations, do all drawing in a JPanel or JComponent's paintComponent method. Get the image's Graphics object only when you need it and dispose of it when you're done with it. For example: