2014-12-28 1 views
3

삼각형을 그릴 코드를 만들어야합니다. 사용자는 삼각형 내부 또는 외부를 클릭합니다. "클릭은 삼각형 안에 있습니다"라는 대화 상자가 표시됩니다.마우스 확인 방법 2D Graphics java를 클릭하십시오.

여기에 삼각형을 그리는 코드가 있습니다. 코드는 이제 무엇을해야할까요? 나는 모른다. 하나라도 도와 주시면 부탁드립니다.

축베이스를 사용해 보았지만 필요한 결과가 나오지 않았습니다.

public void paintComponent(Graphics g) 
     { 
      Graphics2D g2 = (Graphics2D) g; 
      g2.draw(new Line2D.Double (150, 200, 200, 100)); 
      g2.draw(new Line2D.Double (100, 100, 150, 200));   
      g2.draw(new Line2D.Double (100, 100, 200, 100)); 
     } 

출력은 여기입니다. enter image description here

+0

이 도움이 될 것입니다 http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-triangle – lwi

답변

1

Shape 클래스를 사용하고 싶습니다. 삼각형을 손으로 그리는 대신 (각 줄에 대해 개별 draw 문으로), 삼각형을 나타내는 Shape 개체를 만듭니다. Polygon은 삼각형을 작성하는 데 충분합니다.

JFrame의 페인팅을 변경하는 대신 사용자 정의 페인트 패널을 추가하여 프레임에 추가하는 것이 좋습니다.

public class YourFrame extends JFrame { //Replace with your class name, obviously 

    public YourFrame(){ 
     //Create and add trianglePanel 
     setLayout(new BorderLayout()); 
     add(new TrianglePanel(), BorderLayout.CENTER); 
     pack(); 
     repaint(); 
     setVisible(true); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    class TrianglePanel extends JPanel implements MouseListener{ 
     private Polygon triangle; 

     public TrianglePanel(){ 
      //Create triangle 
      triangle = new Polygon(); 
      triangle.addPoint(150, 200); 
      triangle.addPoint(100, 100); 
      triangle.addPoint(200, 100); 

      //Add mouse Listener 
      addMouseListener(this); 

      //Set size to make sure that the whole triangle is shown 
      setPreferredSize(new Dimension(300, 300)); 
     } 

     /** Draws the triangle as this frame's painting */ 
     public void paintComponent(Graphics g){ 
      Graphics2D g2d = (Graphics2D)g; 
      g2d.draw(triangle); 
     } 

     //Required methods for MouseListener, though the only one you care about is click 
     public void mousePressed(MouseEvent e) {} 
     public void mouseReleased(MouseEvent e) {} 
     public void mouseEntered(MouseEvent e) {} 
     public void mouseExited(MouseEvent e) {} 

     /** Called whenever the mouse clicks. 
      * Could be replaced with setting the value of a JLabel, etc. */ 
     public void mouseClicked(MouseEvent e) { 
      Point p = e.getPoint(); 
      if(triangle.contains(p)) System.out.println("Triangle contains point"); 
      else System.out.println("Triangle Doesn't contain point"); 
     } 
    } 
}   
+0

나는 그것을 얻지 못했지만 시도하도록 노력했다. 그 다음 나는 내가 약간의 문제가 있는지 물을 것이다. 감사합니다 –

+0

삼각형을 패널로 페인트하도록 변경되었습니다. 내가 이것을 코딩한다면 어떻게 할 수 있겠는가. – Mshnik

+0

이 라인에 오류가 있습니다 addPoint 기능이 없습니다 .... triangle.addPoint (150, 200); triangle.addPoint (100, 100); triangle.addPoint (200, 100); –

-1

이 작업을 수행해야합니다. 그것은 최선의 선택이 아니며 최고의 성능을 가진 것도 아닙니다.

// The main class which makes the frame and adds the necessary stuff 
class Mainclass { 
    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setSize(400,400); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     CPanel panel = new CPanel(); 

     // I like colours 
     panel.setBackground(new Color(255,255,255,255)); 
     frame.add(panel); 

     frame.addMouseListener(new Mouse(panel)); 

     frame.setVisible(true); 
    } 
} 

// The MouseListener which checks if the mouse is clicked 
class Mouse implements MouseListener { 

    CPanel panel; 

    public Mouse(CPanel panel) { 
     this.panel=panel; 
    } 


    @Override 
    public void mouseClicked(MouseEvent e) { 
     int x=e.getX(); 
     int y=e.getY(); 

     boolean inside=false; 

     ArrayList<Integer> Ys = panel.coordinates.get(x); 
     if(Ys != null) { 
      if(panel.coordinates.get(x).contains(y)) { 
       inside=true; 
      } 
     } 

     if(inside) { 
      System.out.println("You clicked in the triangle"); 
     } else { 
      System.out.println("You clicked out of the triangle"); 
     } 

    } 

    @Override public void mousePressed (MouseEvent e) {} 
    @Override public void mouseReleased (MouseEvent e) {} 
    @Override public void mouseEntered (MouseEvent e) {} 
    @Override public void mouseExited (MouseEvent e) {} 
} 

// The panel 
class CPanel extends JPanel { 

    public int minX=100; 
    public int maxX=200; 
    public int minY=100; 
    public int maxY=200; 

    // All the pixels in the triangle 
    HashMap<Integer, ArrayList<Integer>> coordinates = new HashMap<Integer, ArrayList<Integer>>(); 


    public void paintComponent(Graphics G) { 
     super.paintComponent(G); 

     /** For that one downvoter: I made it G2D, even though it makes no difference **/ 
     Graphics2D g = (Graphics2D) G; 

     // Drawing a centered triangle 
     int xCen=(int)Math.round((minX+maxX)/2.0); 

     // I like colours 
     g.setColor(new Color(0,0,255,128)); 

     for(int y=0; y<=maxY-minY; y++) { 

      int x0=xCen-y; 
      int x1=xCen+y; 

      int y0=y+minY; 

      for(int x=x0; x<=x1; x++) { 
       // Adding all pixels in this row to 'coordinates' 
       ArrayList<Integer> Ys = coordinates.get(x); 

       if(Ys==null) { 
        coordinates.put(x, new ArrayList<Integer>()); 
        Ys = coordinates.get(x); 
       } 

       Ys.add(y0); 
       coordinates.put(x, Ys); 
      } 

      // Draw the row 
      g.drawLine(x0,y0,x1,y0); 
     } 

     // Output the coordinates for debugging purposes 
     System.out.println(coordinates); 
    } 
} 

더 나은 성능을 원하는 제품을 원한다면 사용하지 마십시오.

@Mshink의 도움으로
+0

삼각형 드로잉 코드, 어떻게 작동합니까? 약 삼각형 삼각형 (Sierpinski triangle)을 만들 필요가 있습니다. 루프는 좋은 옵션이 아닐 것입니다 ... –

+0

@AdnanAli 그 말은 제가 두 번 말했던 것입니다. 최고의 성능을 가진 것은 아니지만, 어떻게해야 할 지에 대한 아이디어를 얻을 수 있습니다. – Charlie

0

최종 코드

public class Triangle_shape extends JFrame { 
     /** 
     * @param args the command line arguments 
     */ 
     public Triangle_shape(){ 
      //Create and add trianglePanel 

      // setVisible(true); 
     // setDefaultCloseOperation(EXIT_ON_CLOSE); 
     } 
     public static void main(String[] args) { 

      // TODO code application logic here 
      TrianglePanel t= new TrianglePanel(); 
     JFrame frame = new JFrame(); 
     final int FRAME_WIDTH = 500; 
     final int FRAME_HEIGHT = 500; 

     frame.setSize (FRAME_WIDTH, FRAME_HEIGHT);   

     frame.setLayout(new BorderLayout()); 
      frame.add(t); 
     // frame.add(new TrianglePanel(), BorderLayout.CENTER); 
      frame.pack(); 
      frame.repaint(); 
      frame.setTitle("A Test Frame"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 

     } 
     public static class TrianglePanel extends JPanel implements MouseListener{ 
      private Polygon triangle; 

      public TrianglePanel(){ 
       //Create triangle 
       triangle = new Polygon(); 
       triangle.addPoint(150, 200); 
       triangle.addPoint(100, 100); 
       triangle.addPoint(200, 100); 

       //Add mouse Listener 
       addMouseListener(this); 

       //Set size to make sure that the whole triangle is shown 
       setPreferredSize(new Dimension(300, 300)); 
      } 

      /** Draws the triangle as this frame's painting */ 
      public void paintComponent(Graphics g){ 
       Graphics2D g2d = (Graphics2D)g; 
       g2d.draw(triangle); 
      } 

      //Required methods for MouseListener, though the only one you care about is click 
      public void mousePressed(MouseEvent e) {} 
      public void mouseReleased(MouseEvent e) {} 
      public void mouseEntered(MouseEvent e) {} 
      public void mouseExited(MouseEvent e) {} 

      /** Called whenever the mouse clicks. 
       * Could be replaced with setting the value of a JLabel, etc. */ 
      public void mouseClicked(MouseEvent e) { 
       Point p = e.getPoint(); 
       if(triangle.contains(p)) System.out.println("Triangle contains point"); 
       else System.out.println("Triangle Doesn't contain point"); 
      } 




     } 
    } 
관련 문제