Search code examples
javaswingjframedrawingdda

How can I implemented DDA at JFrame?


I tried to create implementation DDA line drawing algorithm at Java. I created JFrame form and dda.java classes. There is just one Button action at JFrame for this moment. And I am not sure about implementation DDA at JFrame class. I think, that it might be problem with drawPixel method but I am not sure about implementation at JFrame at all. I appreciate your comments.

this is draw line method at dda.java

 void drawLineDDA(Graphics2D g) {
        dx=(double)(x2-x1);
        dy=(double)(y2-y1);
        double m=Math.abs(dy/dx);
        double absx=Math.abs(dx);
        double absy=Math.abs(dy);
        double px = absx/p; 
        double py = absy/p; 
        int p=0;
        float slope = 1; 

        if(y1==y2){
            if(x1==x2) return; //it is not a line, nothing happened
            slope = 0;
            absx = 1;
            absy = 0;
            p=(int) (dx/absx); //p means number of steps
        }
        else if(x1==x2){
            slope = 2;
            absx = 0;
            absy = 1;
            p = (int) (dy/absy);
        }
        else{
            slope = (float) (dy/dx);
            absx=1;
            absy=slope*absx;
            p= (int) ((dy/absy > dx/absx) ? dy/absy : dx/absx);
        }
        for(int i = 0; i <=p;i++){

            drawPixel(x1,y1,Color.BLACK);

            x1 += absx;
            y1 += absy;
        }}

method draw Pixel at dda.java

private void drawPixel(int x1, int y1, Color BLACK) {
      g.drawOval(x1, y1, x1+5, y1+5); //can be mistake right here?
    }

part of JFrame class

public class NewJFrame extends javax.swing.JFrame {
    int x1,x2,y1,y2;
 Graphics2D g;
 dda d;


    public NewJFrame() {
        this.d = new dda(20,30,20,50); //maybe this is not good?
        initComponents();

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
         g = (Graphics2D) jPanel1.getGraphics();
        d.drawLineDDA(g);   // and I am definielly not sure about this
    }

Solution

  • You should not use getGraphics() for custom painting, as it is a temporary buffer which is recycled on next repaint. Do you painting in paintComponent(). Override paintComponent() method of a JComponent or JPanel. See Performing Custom Painting for more information and examples. Also see Painting in AWT and Swing.

    There is also an issue in drawPixel method, as the dimensions of the oval depend on the coordinates. Try using constant dimension. fillOval may suit better. Here is an example:

    private void drawPixel(Graphics2D g, int x1, int y1) {
        g.fillOval(x1, y1, 3, 3);
    }