2015-01-24 4 views
1

임의의 반지름 길이로 20 개의 무작위 원을 생성하는 프로그램을 작성해야합니다. 이 원 중 하나가 다른 원과 교차하면 원은 파란색이어야하며 교차하지 않으면 색상이 빨간색입니다. 또한 JFrame에 버튼을 배치해야합니다. 이 버튼을 누르면 JFrame을 지우고 동일한 색상 규칙에 따라 새로운 20 개의 원 세트를 생성해야합니다. 나는 Java Swing에 매우 익숙하며 정말로 붙어 있습니다. 나는 버튼을 제외한 모든 것을 가지고있다. 생성 할 새로운 서클 집합을 가져올 수 없습니다. 어떤 도움이라도 대단히 감사하겠습니다. 고맙습니다.버튼 JFrame의 뷰를 재설정하려면

import java.awt.Graphics; 
import javax.swing.JPanel; 
import java.util.Random; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 

public class IntersectingCircles extends JPanel 
{ 
    private int[] xAxis = new int [20]; // array to hold x axis points 
    private int[] yAxis = new int [20]; // array to hold y axis points 
    private int[] radius = new int [20]; // array to hold radius length 


    public static void main (String[] args) 
    { 
     JFrame frame = new JFrame("Random Circles"); 
     frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add (new IntersectingCircles()); 

     frame.pack(); 
     frame.setVisible(true); 
    } 

    public IntersectingCircles() 
    { 
     setPreferredSize(new Dimension(1000, 800)); // set window size 

     Random random = new Random(); 

     // Create coordinates for circles 
     for (int i = 0; i < 20; i++) 
     { 
      xAxis[i] = random.nextInt(700) + 100; 
      yAxis[i] = random.nextInt(500) + 100; 
      radius[i] = random.nextInt(75) + 10; 
     } 
    } 

    public void paintComponent(Graphics g) 
    { 
     // Add button to run again 
     JButton btnAgain = new JButton("Run Again"); 
     btnAgain.setBounds(850, 10, 100, 30); 
     add(btnAgain); 
     btnAgain.addActionListener(new ButtonClickListener()); 

     // Determine if circles intersect, create circles, color circles 
     for (int i = 0; i < 20; i++) 
     { 
      int color = 0; 

      for (int h = 0; h < 20; h++) 
      {    
       if(i != h) 
       { 
        double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0; 

        x1 = (xAxis[i] + radius[i]); 
        y1 = (yAxis[i] + radius[i]); 
        x2 = (xAxis[h] + radius[h]); 
        y2 = (yAxis[h] + radius[h]); 

        d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1)))); 

        if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h]))) 
        { 
         color = 0; 
        } 

        else 
        { 
         color = 1; 
         break; 
        } 
       } 
      } 

      if (color == 0) 
      { 
       g.setColor(Color.RED); 
       g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2); 
      } 

      else 
      { 
       g.setColor(Color.BLUE); 
       g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2); 
      } 
     } 
    } 

    private class ButtonClickListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String action = e.getActionCommand(); 
      if(action.equals("Run Again")) 
      { 
       new IntersectingCircles(); 
      } 
     } 
    } 
} 
+1

1) 자바 GUI를 다른 OS ', 화면 크기, 화면 해상도 등 이와 같이 작업을해야, 그들은 픽셀에 도움이되지 않습니다 완벽한 레이아웃. 대신 레이아웃 관리자 또는 [조합] (http://stackoverflow.com/a/5630271/418556)과 [공백] 레이아웃 채우기 및 테두리 (http://stackoverflow.com/a/17874718/)를 사용하십시오. 418556). 2) [Java Swing에서 set (Preferred | Maximum | Minimum) Size 메소드를 사용하지 않는 것이 좋겠습니까?] (예.) 3 참조) [Collision 복잡한 모양의 탐지] (http://stackoverflow.com/a/14575043/418556)를 참조하십시오. –

+1

@HovercraftFullOfEels 첫번째 나는 그 찌끼를 보았습니다. 끝난! –

+0

@AndrewThompson : 감사합니다! –

답변

2

제안 :

  • 이 클래스 임의 원과 통화를 다시 칠 생성하는 방법을 지정()
  • 원을 만들고 ArrayList에에 추가한다이 방법.
  • 서클을 나타내는 데 Ellipse2D를 사용하는 것이 좋으므로 ArrayList<Ellipse2D>이 있어야합니다.
  • 클래스 생성자에서이 메서드를 호출하십시오.
  • 버튼의 ActionListener에서 다시 호출하십시오.
  • paintComponent 메소드 내에서 버튼의 상태를 변경하거나 클래스의 상태를 변경하지 마십시오. 이 메소드는 원을 그리고 그리기 위해서만 사용됩니다. paintComponent 메서드가 호출 될 때마다 버튼을 만드는 방식이므로 많은 JButton을 불필요하게 생성 할 수 있으므로
  • 번 불필요하게 시간이 중요한 그림 메서드를 느리게 만들 수 있습니다.
  • 대신 생성자에 버튼을 추가하십시오.
  • 첫 번째 호출로 paintComponent 메서드에서 super.paintComponent(g)을 호출해야합니다. 필요한 경우 이전 서클을 삭제합니다.
  • 또한 paintComponent에서 원의 ArrayList를 반복하여 각각을 그립니다.
0

이 웹 사이트에서 일부 검색을 한 후 필요한 것을 찾았습니다. 모든 것이 이제는 효과가있는 것 같습니다. 감사. 당신이 시도 할 수 있습니다 어쩌면

import java.awt.Graphics; 
import javax.swing.JPanel; 
import java.util.Random; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.ActionListener; 
import java.awt.event.ActionEvent; 

public class IntersectingCircles extends JPanel 
{ 
    private int[] xAxis = new int [20]; // array to hold x axis points 
    private int[] yAxis = new int [20]; // array to hold y axis points 
    private int[] radius = new int [20]; // array to hold radius length 


    public static void main (String[] args) 
    { 
     JFrame frame = new JFrame("Random Circles"); 
     frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); 
     frame.setPreferredSize(new Dimension(1000, 800)); 

     ActionListener runAgain = new ActionListener() 
     { 
      @Override 
      public void actionPerformed(ActionEvent c) 
      { 
       frame.getContentPane().add(new IntersectingCircles()); 
       frame.pack(); 
      } 
     }; 

     JButton btnAgain = new JButton("Run Again"); 
     btnAgain.setBounds(850, 10, 100, 30); 
     btnAgain.addActionListener(runAgain); 


     frame.add(btnAgain);   
     frame.getContentPane().add (new IntersectingCircles());  
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public IntersectingCircles() 
    {  
     Random random = new Random(); 

     // Create coordinates for circles 
     for (int i = 0; i < 20; i++) 
     { 
      xAxis[i] = random.nextInt(700) + 100; 
      yAxis[i] = random.nextInt(500) + 100; 
      radius[i] = random.nextInt(75) + 10; 
     } 
    } 

    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     // Determine if circles intersect, create circles, color circles 
     for (int i = 0; i < 20; i++) 
     { 
      int color = 0; 

      for (int h = 0; h < 20; h++) 
      {    
       if(i != h) 
       { 
        double x1 = 0, x2 = 0, y1 = 0, y2 = 0, d = 0; 

        x1 = (xAxis[i] + radius[i]); 
        y1 = (yAxis[i] + radius[i]); 
        x2 = (xAxis[h] + radius[h]); 
        y2 = (yAxis[h] + radius[h]); 

        d = (Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1)*(y2 - y1)))); 

        if (d > radius[i] + radius[h] || d < (Math.abs(radius[i] - radius[h]))) 
        { 
         color = 0; 
        } 

        else 
        { 
         color = 1; 
         break; 
        } 
       } 
      } 

      if (color == 0) 
      { 
       g.setColor(Color.RED); 
       g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2); 
      } 

      else 
      { 
       g.setColor(Color.BLUE); 
       g.drawOval(xAxis[i], yAxis[i], radius[i] * 2, radius[i] * 2); 
      } 
     } 
    } 
} 
0
private class ButtonClickListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      repaint(); 
     } 
    } 

...