2011-04-10 53 views
2

如何在此代码中查找变量g?我想从paintComponent中使用fillRect画线。 请帮忙。如何在这段代码中找到变量g?

import java.awt.*; 
import java.lang.String.*; 
import java.util.Scanner; 
import java.io.IOException; 
import javax.swing.*; 

class Test extends JPanel { 
    public static void main(String[] args) { 
     String x1; 
     String x2; 
     String y1; 
     String y2; 

     Scanner sc = new Scanner(System.in); 
     System.out.print("Podaj pierwsza wspolrzedna pierwszego punktu: "); 
     x1 = sc.nextLine(); 
     System.out.print("Podaj druga wspolrzedna pierwszego punktu: "); 
     x2 = sc.nextLine(); 
     System.out.print("Podaj pierwsza wspolrzedna drugiego punktu: "); 
     y1 = sc.nextLine(); 
     System.out.print("Podaj druga wspolrzedna drugiego punktu: "); 
     y2 = sc.nextLine(); 

     Test nowy = new Test(); 
     DDA2 dda2 = new DDA2(); 
     dda2.licz(x1, x2, y1, y2); 

     JFrame ramka = new JFrame(); 
     ramka.setSize(300,300); 
     ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     ramka.getContentPane().add(new Test()); 
     ramka.setVisible(true); 

    } 


} 



class DDA2 { 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     g.setColor(Color.RED); 
    } 



    public void licz(String xx1, String xx2, String yy1, String yy2){ 
     double dxx1 = Double.parseDouble(xx1); 
     double dxx2 = Double.parseDouble(xx2); 
     double dyy1 = Double.parseDouble(yy1); 
     double dyy2 = Double.parseDouble(yy2); 
     double dx = dxx2 - dxx1; 
     double dy = dyy2 - dyy1; 

     if (Math.abs(dx) >= Math.abs(dy)) 
     { 
      double m = Math.abs(dx); 
      System.out.println("DX" + m); 
     } 
     else 
     { 
      // ALGORYTYM PRZYROSTOWY 
      double m = Math.abs(dy); 
      //System.out.println("DY" + m); 
      double x = dxx1; 
      double y = dyy1; 
      for (int i=1; i <= m; i++) 
      { 
       x = x + dx/m; 
       y = y + dy/m; 
       g.fillRect((int) x, (int) y, 1, 1); 
      } 
     } 

    System.out.println("Wspolrzednie punktu pierwszego to: " + "(" + dxx1 + "; " + dxx2 +")"); 
    System.out.println("Wspolrzednie punktu drugiego to: " + "(" + dyy1 + "; " + dyy2 + ")"); 
    } 
} 
+0

没有变量'g' ... im不知道你在找什么... – Neal 2011-04-10 14:05:44

+0

是有 - 它在paintComponent中提到 – 2011-04-10 14:13:55

回答

2

您需要覆盖扩展JPanel的类(即Test类)中的paintComponent(Graphics g)方法。你在类DDA2中写了一个paintComponent方法,但是什么都不做。

在paintComponent方法里面,你可以调用:

g.fillRect(x, y, w, h); 
1

除了什么文森特说,它看起来像你想拥有fillRect发生在你的licz方法。没问题。只需拨打paintComponent方法中的licz方法即可。 (顺便说一下,如果你的方法与paintComponent方法定义在同一个类中,最简单的方法就是这样。)