2014-09-21 6 views
4

이 문제에 대한 해결책을 찾기 위해 계속 노력해 왔지만이를 해결하는 방법을 이해할 수없는 것 같습니다. Java에서 사용자 입력을 기반으로 원을 그립니다.

  1. 가 입력 상자 (JOptionPane의)를 사용하여 원의 반지름의 사용자에게 질문

    나는 프로그램에서 이러한 사양의 원을 그릴 수있는 간단한 프로그램을 작성하는 것을 시도하고있다.
  2. 사용자에게 입력 상자 (JOptionPane)에서 원의 x 및 y 좌표를 문의하십시오.
  3. 원의 둘레를 계산하십시오.
  4. 원의 면적을 계산하십시오.
  5. 원의 그림 아래 영역 및 원주를 표시합니다.

어떻게 든 원을 그리지 않고 원주와 면적을 계산합니다. 이 문제에 대한 해결책을 찾도록 도와 주시겠습니까?

다음은 내 코드 :

-------

package circleSquarePackage; 

import circleSquarePackage.Circle; 

import javax.swing.JOptionPane; 
import javax.swing.JFrame; 

public class CircleTester { 

    public static void main(String[] args) 
     { 

     JFrame frame = new JFrame(); 

     // Display Circle in the frame 
     frame.setSize(600, 500); 
     frame.setTitle("CircleSquare"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     // Create Circle Components 
     Circle round = new Circle(); 
     frame.add(round); 

     frame.setVisible(true); 

    } 

} 

------- 주요

-------- 다른 클래스 ----- PEESKILLET 'S 답변에 따라 ----

package circleSquarePackage; 

import javax.swing.JComponent; 
import java.awt.geom.Ellipse2D; 
import java.awt.geom.Ellipse2D.Double; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Color; 

import javax.swing.JOptionPane; 


public class Circle extends JComponent { 
    // Member instance field 
    private Ellipse2D.Double sphere; 
    private int radius; 
    double circumference, area; 

    String x1; // starting x co-ordinate 
    String y1; // starting y co-ordinate 
    String r1; // radius for circle 
    String draw; 

    int x = 0; 
    int y = 0; 
    int r = 0; 


    // Default constructor 
    public Circle() 
    { 
     sphere = new Ellipse2D.Double(); 
    } 

    // User defined constructor 
    public Circle(int xAxis, int yAxis, int rad) 
    { 
     rad = r; 
     xAxis = x; 
     yAxis = y; 
     sphere = new Ellipse2D.Double(xAxis, yAxis, rad, rad); 
    } 

    // Accessor methods 
    public double calcCircumference() 
    { 
    return circumference = 2 * Math.PI * radius; 
    } 

    public double calcArea() 
    { 
     return area = Math.PI * radius * radius; 
    } 

    // Methods 
    public void inputX() 
    { 
     x1 = JOptionPane.showInputDialog(null, "Input center (x value): "); 
     x = Integer.parseInt(x1); 
    } 

    public void inputY() 
    { 
     y1 = JOptionPane.showInputDialog(null, "Input center (y value): "); 
     y = Integer.parseInt(y1); 

    } 

    public void inputRadius() 
    { 
     r1 = JOptionPane.showInputDialog(null, "Input radius: "); 
     r = Integer.parseInt(r1); 
    } 

    public void paintComponent(Graphics g) 
    { 
     // Cast 1D to 2D graphics 
     Graphics2D g2 = (Graphics2D) g; 

     g2.setColor(Color.BLUE); // set circle color to blue 
     g2.fill(sphere); 
     g2.draw(sphere); 

     g2.setColor(Color.BLUE); 
     g2.drawString("Circumference = " + calcCircumference(), 5, 450); 
     g2.drawString("Area = " + calcCircumference(), 200, 450); 
    } 
} 

UPDATE

012 3,516,

package circleSquarePackage; 

import javax.swing.JComponent; 
import java.awt.geom.Ellipse2D; 
import java.awt.geom.Ellipse2D.Double; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Color; 
import java.awt.Dimension; 

import javax.swing.JOptionPane; 


public class Circle extends JComponent { 
    // Member instance field 
    private Ellipse2D.Double sphere; 
    private int radius; 
    double circumference, area; 


    // Default constructor 
    public Circle() 
    { 
     sphere = new Ellipse2D.Double(); 
    } 

    public void setSphere(Ellipse2D.Double sphere) { 
     this.sphere = sphere; 
     repaint(); 
    } 

    // User defined constructor 
    public Circle(int xAxis, int yAxis, int rad) 
    { 
     sphere = new Ellipse2D.Double(xAxis, yAxis, rad, rad); 
    } 

    // Accessor methods 
    public double calcCircumference() 
    { 
    return circumference = 2 * Math.PI * radius; 
    } 

    public double calcArea() 
    { 
     return area = Math.PI * radius * radius; 
    } 

    // Methods 
    public void inputX() 
    { 
     int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter x")); 
     double y = sphere.y; // why is there a double y here when it asks for x? 
     Ellipse2D.Double newSphere = new Ellipse2D.Double(x, y, size, size); 
     setSphere(newSphere); 
    } 

    public void inputY() 
    { 
     int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter y")); 
     double x = sphere.x; 
     Ellipse2D.Double newSphere = new Ellipse2D.Double(x, y, size, size); 
     setSphere(newSphere); 
    } 

    public void inputRadius() 
    { 
     // is this how I do for radius? 
     int r = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter radius")); 
     int size = r * 2; 
     Ellipse2D.Double newSphere = new Ellipse2D.Double(x, y, size, size); 
     setSphere(newSphere); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 

     g2.setColor(Color.BLUE); // set circle color to blue 
     g2.fill(sphere); 
     g2.draw(sphere); 

     g2.drawString("Circumference: " + calcCircumference(), 5, 490); 

    } 

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

-------- CircleTester 클래스, 당신은 sphere 당신의 인수 없음의 Circle 생성자에서

package circleSquarePackage; 

import circleSquarePackage.Circle; 

import javax.swing.JOptionPane; 
import javax.swing.JFrame; 
import javax.swing.SwingUtilities; 
import java.awt.geom.Ellipse2D; 
import java.awt.geom.Ellipse2D.Double; 

public class CircleTester { 
    /* 
    private static Ellipse2D.Double getCircle() { 
     int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter integer for x-coordinates:")); 
     int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter integer for y-coordinates:")); 
     int radius = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter radius of circle:")); 
     int size = radius * 2; 
     return new Ellipse2D.Double(x, y, size, size); 
    }*/ 

    public static void main(String[] args) 
    { 
     // Is there a way to call the inputX(), inputY(), and inputRadius() here? 

     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame frame = new JFrame(); 


       frame.setTitle("CircleSquare"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

       Circle round = new Circle(); 
       frame.add(round); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

       /* 
       Ellipse2D.Double newCircle = getCircle(); 
       round.setSphere(newCircle); 
       */ 
      } 
     }); 

    } 

} 

답변

5

만드는 -------- Circle 클래스 (기본값은 Ellipse2D.Double). 당신이 위치로 초기화 Ellipse2D.Double

Ellipse2D.Double()
에서

새로운이 Ellipse2D를 구축 세, 인수 생성자에있는 것처럼 당신은 그 값에 sphere기반을 만들어야합니다 (0, 0) 및 크기 (0, 0).

  1. 또 다른 디자인의 가능성은 타원을 설정하고

    public void setSphere(Ellepse2D.Double sphere) { 
        this.sphere = sphere; 
        repaint(); 
    } 
    
  2. 의 모든 JOptionPane 여전히 후 작업을 수행 칠 수는 Circle 클래스의 setSphere 방법을 가지고 프레임이 표시됩니다. 그냥 맞는 것 같습니다.그런 다음 값을 가져 오면 Circle 클래스에서 Ellipse2D.Double으로 setSphere으로 전화를 걸면이 값이 패널에 표시됩니다.

기타 참고 : 사용자 지정 그림을 수행 할 때

  • , 더 그린 구성 요소에 getPreferredSize()을 무시하고, 단지 setSize()

  • 참조 대신, 프레임에 pack() 전화 초기 스레드. 스윙 앱은 Event Dispatch Thread에서 실행되어야합니다.

  • 또한 Circle 클래스의 중복 x, y, etc 값이 필요하지 않습니다. 그들은 이미 Ellipse 개체에 의해 개최되고 있습니다. 당신이 어떤 값을 얻을 필요가있는 경우, 다만, 그에서 그것을 얻을 즉 sphere.x, sphere.y.

여기에 내가 위에서 언급 한 제안의 리팩토링이 있습니다. 내가 넣을 수 있는지 궁금

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.geom.Ellipse2D; 
import javax.swing.JComponent; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.SwingUtilities; 

public class CircleTester { 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       JFrame frame = new JFrame(); 

       frame.setTitle("CircleSquare"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

       Circle round = new Circle(); 
       frame.add(round); 

       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 

       Ellipse2D.Double newCircle = getCircle(); 
       round.setSphere(newCircle); 
      } 
     }); 

    } 

    private static Ellipse2D.Double getCircle() { 
     int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter x")); 
     int y = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter x")); 
     int radius = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter x")); 
     int size = radius * 2; 
     return new Ellipse2D.Double(x, y, size, size); 
    } 
} 

class Circle extends JComponent { 

    private Ellipse2D.Double sphere; 

    public Circle() { 
     sphere = new Ellipse2D.Double(); 
    } 

    public void setSphere(Ellipse2D.Double sphere) { 
     this.sphere = sphere; 
     repaint(); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 

     g2.setColor(Color.BLUE); // set circle color to blue 
     g2.fill(sphere); 
     g2.draw(sphere); 

    } 

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

UPDATE (당신은 또한 확실히 수. 내가 게으른 실제로 입력 당하고되어 있는지 확인하기 위해 몇 가지 검사를 수행 할 것입니다) JOptionPane은 public void inputX(), public void inputY() 및 public void inputRadius()에서 Circle 클래스의 사용자 입력을 요구 한 다음 CircleTester 클래스의 main에있는 사용자를 호출합니다.

각 메소드에서 JOPtionPane을 호출하면됩니다. 그냥 x를 얻고 싶다면 JOptionPane을 호출하고, 그 값에 따라 이전 값을 사용하고 새로운 x를 사용하여 오래된 Ellipse에서 새로운 Ellipse를 만듭니다. 그런 다음 setSphere으로 전화하십시오. 예 :

public void inputX() { 
    int x = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter x")); 
    double y = sphere.y; 
    double height = sphere.height; 
    double width = sphere.width; 
    Ellips2D.Double newSpehere = new Ellipse2D.Double(x, y, width, height); 
    setSphere(newSphere); 
} 

이렇게하면 다른 사람도 할 수 있습니다. 이 방법은 메서드를 호출 할 때 입력하면 변수 하나만 변경됩니다.

내 예제에서와 같이 모든 변수를 가져 오는 한 가지 방법을 사용할 수도 있습니다.

+0

도움 주셔서 감사합니다. 이 작품! JOptionPane을 public void inputX(), public void inputY() 및 public void inputRadius()의 Circle 클래스에 사용자 입력을 요청한 다음 CircleTester 클래스의 주 사용자에게 호출하는 방법을 궁금합니다. 위의 코드를보고 내가 말하는 것을 볼 수 있습니다. – user3768057

+0

당신이 할 수있는 것은 각 메소드에서'JOPtionPane'을 호출하는 것입니다. 그냥 x를 얻고 싶다면 JOptionPane을 호출하고, 그 값에 따라 이전 값을 사용하고 새로운 x를 사용하여 오래된 Ellipse에서 새로운 Ellipse를 만듭니다. 그런 다음'setSphere'를 호출하십시오. 제발 잠깐 내게 –

+0

보기 내 ** 업데이트 ** –

3
  1. 모든 JOptionPane 호출을 제거하는 것을 의미하는 모든 UI를 Circle 클래스에서 가져옵니다.
  2. 모든 사용자 상호 작용은 CircleTester 클래스에 있어야합니다.
  3. Circle 클래스는 대신 사용자 IO가 아닌 해당 속성으로 정의 된 Circle을 그리는 데 집중해야합니다.
  4. Circle 클래스에 의미있는 매개 변수를 사용하는 생성자를 지정합니다.
  5. g.drawOval (....)`을 호출하여 Graphics 객체로 원을 그릴 수 있으므로 Ellipse2D가 필요하지 않으므로 프로그램이 단순 해집니다.
  6. CircleTester에서 입력 매개 변수를 얻은 다음 CircleTest에서 가져온 매개 변수를 전달하는 Circle 객체를 만들고 Circle을 표시합니다.
  7. 또한 paintComponent 메소드 오버라이드 내에서 super.paintComponent (g) 메소드를 호출하는 것을 잊지 마십시오.
  8. 작은 니트릭이지만 원주와 면적 변수를 선언하지 않고 오히려 서클 클래스 getCircumference()getArea()을 필요에 따라 현장에서 계산하는 방법을 제공합니다. 그렇지 않으면 Circle에 setRadius(...) 메소드를 제공하면 setter 메소드의 다른 필드를 변경해야한다는 것을 기억해야하며 radius 또는 다른 필드를 공개하면 모든 heck가 느슨해 질 수 있습니다. 안전하게 재생하고 필드가 아닌 해당 두 속성에 대한 접근 자 메서드 만 있으면됩니다.