user3085307
user3085307

Reputation: 1

Fiddling with Java Graphics, this worked _once_

I'm trying to draw on a JPanel more directly, hence the following code:

import java.awt.*;
import javax.swing.*;
import java.awt.geom.*;
public class px{
    JFrame F=new JFrame();
    JPanel P=new JPanel();
    public px(){
        P.setPreferredSize(new Dimension(400,300));
        F.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        F.add(P);
        F.pack();
        F.setResizable(false);
        F.setVisible(true);
    }
    public void sq(int x,int y,int c){
        Graphics2D G=(Graphics2D)P.getGraphics();
        G.setPaint(Color.red);
        G.fill(new Rectangle(x*10,y*10,10,10));
        P.paint(P.getGraphics());
        F.revalidate();
    }
    public static void main (String[]args){
        px X=new px();
        X.sq(1,1,0);
    }
}

However the damned little red square has only appeared once, might have been a runtime error or a botched compile.

Upvotes: 0

Views: 71

Answers (1)

Braj
Braj

Reputation: 46841

  • Override paintComponent() method of JPanel for custom painting where you can get the Graphics object as method parameters.

  • Don't forget to call super.paintComponent() in overridden paintComponent() method.

  • Override getPreferredSize() to set the preferred size of the JPanel in case of custom painting.

For more info read Lesson: Performing Custom Painting and try sample code as well.

Note: Follow Java Naming convention.

sample code:

class MyPanel extends JPanel {
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        ...
        // custom painting code goes here
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(..., ...);
    }
}

Upvotes: 2

Related Questions