2014-09-07 2 views
0

충분한 단어로 설명하는 방법이 확실치 않아 다른 해결책을 찾을 수 없습니다.Java 오브젝트 값이 일치하지 않습니다.

필드에 currentActiveList이라는 임의로 생성 된 사각형을 ActiveList 클래스에 할당하면 값이 정상적으로 수신됩니다. 그러나

public class ActiveList { 
    Rectangle[] activeList = new Rectangle[10]; 

    public ActiveList() { 
     for(int i = 0; i < activeList.length; i++) 
      activeList[i] = null; 
    } 

    public void addToList(Rectangle x) { 
     for(int i = 0; i < this.activeList.length; i++) { 
      if(this.activeList[i] == null) { 
       this.activeList[i] = x; 
       i = this.activeList.length+1; 
      } 

      else 
       this.activeList[activeList.length-1] = x; 
     } 
    } 

    public Rectangle[] getActiveList() { 
     return this.activeList; 
    } 

    public int getLength() { 
     //System.out.print(this.activeList.length); 
     return this.activeList.length; 
    } 

    public void deleteFromList(int x) { 
     this.activeList[x] = null; 
    } 

    public Rectangle getFromList(int x) { 
     Rectangle retVal = this.activeList[x]; 
     //System.out.println("Returning getFromList(int x): " +retVal); 
     return retVal; 
    } 

    public void genRandomRectangle() { 
     Random randomNumberGenerator = new Random(); 
     double[] pointVal = new double[4]; 
     double randomInt = randomNumberGenerator.nextInt(400-10); 
     pointVal[0] = randomInt; 
     randomInt = randomNumberGenerator.nextInt(400-10); 
     pointVal[1] = randomInt; 
     randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[0])); 
     if(randomInt < 5) { 
      randomInt = randomInt+pointVal[0]+5; 
     } 

     else 
      pointVal[2] = randomInt+pointVal[0]; 

     randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[1])); 
     if(randomInt < 5) { 
      randomInt = randomInt+pointVal[1]+5; 
     } 

     else 
      pointVal[3] = randomInt+pointVal[1]; 

     Rectangle newRandom = new Rectangle(pointVal[0], pointVal[1], pointVal[2], pointVal[3]); 
     //System.out.println(pointVal[0]); 
     //System.out.println(pointVal[1]); 
     //System.out.println(pointVal[2]); 
     //System.out.println(pointVal[3]); 
     System.out.println("New Random: " +newRandom); 

     addToList(newRandom); 
    } 
} 

, 내 메인 클래스 GraphicGen에 그 값을 사용하려고, 그 모든 인덱스에 대한 currentActiveList 반환 null 값.

public class GraphicGen extends JPanel { 
    ActiveList currentActiveList = new ActiveList(); 
    public static int gridSpaceX = 400; 
    public static int gridSpaceY = 400; 
    static JFrame mainFrame = new JFrame(); 

    protected void paintComponent(Graphics g) { 
     //super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D)g; 
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     //int w = getWidth(); 
     //int h = getHeight(); 
     // Draw ordinate. 
     //g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD)); 
     // Draw abcissa. 
     //g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD)); 
     //double xInc = (double)(w - 2*PAD)/(data.length-1); 
     //double scale = (double)(h - 2*PAD)/maxValue(); 
     // Mark data points. 
     //g2.setPaint(Color.red); 

     double[] coords = new double[4]; 
     //g2.fill(new Ellipse2D.Double(coords[0], coords[1], 4, 4)); 
     //g2.fill(new Ellipse2D.Double(coords[2], coords[3], 4, 4)); 
     //g2.fill(new Ellipse2D.Double(100, 100, 4, 4)); 
     System.out.println("Graphic Gen Active List Obj: " +currentActiveList); 
     System.out.println("Ya drew a new Main GUI!"); 
     System.out.println("currentActiveList.getActiveList(): " +currentActiveList.getActiveList()); 
     for(int i = 0; i < currentActiveList.getLength(); i++) { 
      //System.out.println("currentActiveList.getFromList(i): "+currentActiveList.getFromList(i)); 
      //System.out.println("Graphic Gen Active List Obj: " +currentActiveList); 
      //System.out.println(activeList.getFromList(i).getTopLeftX()); 
      if(currentActiveList.getFromList(i) != null) { 
       coords[0] = currentActiveList.getFromList(i).getTopLeftX(); 
       System.out.println(coords[0]); 
       coords[1] = currentActiveList.getFromList(i).getTopLeftY(); 
       System.out.println(coords[1]); 
       coords[2] = currentActiveList.getFromList(i).getBottomRightX(); 
       System.out.println(coords[2]); 
       coords[3] = currentActiveList.getFromList(i).getBottomRightY(); 
       System.out.println(coords[3]); 
       g2.draw(new Line2D.Double(coords[0], coords[1], coords[2], coords[1])); 
       g2.draw(new Line2D.Double(coords[0], coords[1], coords[0], coords[3])); 
       g2.draw(new Line2D.Double(coords[2], coords[1], coords[2], coords[3])); 
       g2.draw(new Line2D.Double(coords[0], coords[3], coords[2], coords[3])); 
      } 
     } 

     /*double x = 50; 
     double y = 50; 
     g2.fill(new Ellipse2D.Double(x, y, 4, 4));*/ 
     /*for(int i = 0; i < data.length; i++) { 
      double x = PAD + i*xInc; 
      double y = h - PAD - scale*data[i]; 
      g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4)); 
     }*/ 
    } 

    /*private int maxValue() { 
     int max = data[0]; 
     for(int i = 0; i < data.length; i++) { 
      if(data[i] > max) 
       max = data[i]; 
     } 
     return max; 
    }*/ 

    public void callRepaintOnMain() { 
     mainFrame.repaint(); 
    } 

    public void callGenRandom() { 
     currentActiveList.genRandomRectangle(); 
    } 

    public static void main(String[] args) { 
     mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     mainFrame.add(new GraphicGen()); 
     mainFrame.setSize(gridSpaceX, gridSpaceY); 
     ButtonPrompt buttonPrompter = new ButtonPrompt(); 
     mainFrame.setLocation(200,200); 
     mainFrame.setVisible(true); 
    } 
} 

랜덤 생성기 메서드는 동작 수신기에서 호출됩니다.

public class ButtonPrompt extends GraphicGen { 

    ActionListener actionListenerRandom = new ActionListener() { 
     public void actionPerformed(ActionEvent actionEvent) { 
      //currentActiveList.genRandomRectangle(); 
      callGenRandom(); 
      callRepaintOnMain(); 
     } 
    }; 

    JButton randomBtn = new JButton("Add Random Rectangle");   
    JButton inputCoordinates = new JButton("Input Rectangle Coordinates"); 

    public ButtonPrompt() { 
     JFrame f = new JFrame("Add Rectangles"); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     BoxLayout boxLayout = new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS); 
     f.setLayout(boxLayout); 

     randomBtn.addActionListener(actionListenerRandom); 

     f.setSize(200, 200); 
     f.setLocation(600, 200); 
     f.setVisible(true); 
     f.add(randomBtn); 
     f.add(inputCoordinates); 
     f.pack(); 
    } 
} 

범위 지정 또는 참조 문제입니까? 나는 정말로 여기를 잃고있다.

public ActiveList() { 
    for(int i = 0; i < activeList.length; i++) 
     activeList[i] = null; 
} 

위의 코드가 완전히 쓸모 :

+4

메인 클래스 (여기서는'ActiveList' 사용법)를 넣을 수 있습니까? 예를 들어 누가'addToList'를 호출할까요? – coolcfan

+0

잘하면 더 명확하게 업데이트했습니다. – John

+0

사각형 목록에 이미 요소가 10 개있는 경우 코드에서 수행 할 것으로 예상되는 작업은 무엇입니까? – BatScream

답변

1

:

public static void main(String[] args) { 
    ... 
    mainFrame.add(new GraphicGen()); 
    ... 
    ButtonPrompt buttonPrompter = new ButtonPrompt(); 
} 

ButtonPrompt

JPanel GraphicGen을 연장한다. ButtonPrompt의 생성자에서 JFrame을 만들고 그것에 JButton을 두 개 추가했습니다.

앱이 시작되면 화면에 두 개의 JFrame이 표시되고 mainFrame에는 GraphicGen이 포함되고 다른 하나는 buttonPrompter에 두 개의 버튼이 포함됩니다.

버튼을 클릭

actionPerformed()를 호출하고 실제로 buttonPromptercallGenRandom() 부르고 - 무작위 생성 로직이 정확한지 를, 생성 된 사각형은 buttonPrompter에 추가됩니다. 그러나이 buttonPrompterJFrame 중 하나에 추가하지 않으면 표시되지 않습니다.


당신이 할 수 있습니다 무엇 :

ButtonPrompt

GraphicGen를 확장하지 않는 대신, 제공 ButtonPrompt의 참고 문헌 GraphicGen 당신이 mainFrame에 추가됩니다.
public class ButtonPrompt extends GraphicGen { 
    JButton randomBtn = new JButton("Add Random Rectangle");   
    JButton inputCoordinates = new JButton("Input Rectangle Coordinates"); 
    final GraphicGen gg; 

    public ButtonPrompt(GraphicGen gg) { 
     this.gg = gg; 
     ...... 

     ActionListener actionListenerRandom = new ActionListener() { 
      public void actionPerformed(ActionEvent actionEvent) { 
       gg.callGenRandom(); 
       gg.callRepaintOnMain(); 
      } 
     }; 

     randomBtn.addActionListener(actionListenerRandom); 

     ...... 
    } 
} 

하고 main()

은 :

무엇보다
public static void main(String[] args) { 
    ... 
    GraphicGen gg = new GraphicGen(); 
    mainFrame.add(gg); 
    ... 
    ButtonPrompt buttonPrompter = new ButtonPrompt(gg); 
} 

, 코드가 다른 문제가있다. 이 나쁜 보인다 -

예를 들어, GraphicGenJPanel, 메인 클래스이며, 응용 프로그램이 실행될 때 실제로는 GraphicGen 인스턴스가있는 JFrame의 필드가 있습니다. 나는 스윙을 많이 모른다 ... JPanelrepaint()을 호출하는 것 대신에 의 repaint()을 호출해야한다.

+0

두 개의 JFrame이 필요하지만 두 번째 JFrame의 buttonPrompt에서 주 JFrame에서 다시 칠하기를 원합니다. GraphicGen의 확장을 묻는 버튼을 만들지 않고 어떻게 할 수 있습니까? – John

+0

@ 존 내 업데이트를 참조하십시오. – coolcfan

+0

그것은 그것을 훌륭하게 해결했습니다. 고맙습니다. – John

1

귀하의 실제 문제가 매우 불분명하지만, 그냥 내가 생각 무엇을 찾을 정도로 첫 번째 두 가지 방법을 읽고, 버그입니다. 객체 배열의 요소의 기본값은 null입니다. 따라서 루프는 이미 null 인 변수에 null을 할당합니다.

public void addToList(Rectangle x) { 
    for(int i = 0; i < this.activeList.length; i++) { 
     if(this.activeList[i] == null) { 
      this.activeList[i] = x; 
      i = this.activeList.length+1; 
     } 

     else 
      this.activeList[activeList.length-1] = x; 
    } 
} 

목록에 null 만 포함되어 있으면 사각형이 인덱스 0에 저장되고 루프가 중지됩니다. 이 메소드를 호출 할 때 루프는 인덱스 0에있는 요소가 null이 아니므로 배열의 마지막 인덱스에 x를 저장 한 다음 첫 번째 비 null 인덱스에 저장합니다.

나는 당신이 달성하고자하는 것이 무엇인지, 실제 문제는 무엇인지는 모르겠지만 배열을 기반으로 자신 만의 목록을 구현하는 것을 잊어서 ArrayList를 대신 사용해야합니다. 여기

+0

ActiveList 객체의 기본 생성자가 쓸모 없다는 것을 알고, 필사적으로 노력했습니다. 내 문제는 currentActiveList에서 genRandomRectangle()을 호출 할 때 임의의 사각형 만들기가 끝난 후 addToList를 사용하여 현재 객체의 activeList에 무작위 사각형을 할당한다는 것입니다. 그러나 GraphicsGen으로 돌아가서 currentActiveList.getFromList (i)! = null) {가 실행되면 .getFromList (i)는 항상 null을 반환합니다. – John

관련 문제