2014-06-14 2 views
3

그래서 나는 stackoverflow에 새로 왔어.선 그리기, 동그라미 아무것도 (Java)

나는 선, 삼각형을 만들려고하고있다. 그러나 나는 단지 선과 좋은 객체 지향 프로그래밍에 초점을 맞추고있다.

package draw; 

/** 
* 
* @author Pedro 
*/ 
public class Point2D { 
    private int x,y; 

    // Construtores 
    public Point2D(){ 
     this(0,0); 
    } 

    public Point2D(int x, int y){ 
     this.x=x; 
     this.y=y; 
    } 

    // Set's e Get's 
    public int getX() { 
     return x; 
    } 
    public void setX(int x) { 
     this.x = x; 
    } 
    public int getY() { 
     return y; 
    } 
    public void setY(int y) { 
     this.y = y; 
    } 

나중에 내가 시작점과 마지막 점

package draw; 

/** 
* 
* @author Pedro 
*/ 
public class Linha extends Figura{ 
    private Point2D pinicial; 
    private Point2D pfinal; 

    //construtores  
    public Linha(int xinicial, int yinicial, int xfinal, int yfinal){ 
     pinicial=new Point2D(xinicial, yinicial); 
     pfinal=new Point2D(xfinal, yfinal); 
    } 
    public Linha(Point2D pinicial, Point2D pfinal){ 
     this.pinicial=pinicial; 
     this.pfinal=pfinal; 
    } 
    //Get's e Set's 
    public Point2D getPinicial() { 
     return pinicial; 
    } 
    public void setPinicial(Point2D pinicial) { 
     this.pinicial = pinicial; 
    } 
    public Point2D getPfinal() { 
     return pfinal; 
    } 
    public void setPfinal(Point2D pfinal) { 
     this.pfinal = pfinal; 
    } 

} 

을 얻을 수있는 클래스의 Point2D를 사용하여 클래스 라인을 만든 다음 내가 가진 JFrame의 생성 :

그래서 내가 클래스의 Point2D를 만들 "line"이라는 버튼을 클릭하고 jFrame 내부에 패널을 놓습니다.이 패널은 선을 그릴 곳입니다.

문제는 ... 나는 선을 그어야하는지, 어떻게해야 하는지를 모릅니다.

도와 주시겠습니까?

+1

당신이 봤어 다음과 같이

간단한 예는? http://docs.oracle.com/javase/tutorial/uiswing/painting/ – Abrixas2

+2

아, 나는 내 스윙을 닦아야한다. 사실, 내 의견은 너무 틀렸어. 그래서 나는 그것을 대신 삭제할 것이다. 죄송합니다! – EpicPandaForce

답변

4

간단하게, 당신의 JPanel의 클래스 ovverride paintComponent() 방법 : x1는, y1, x2y2, 당신의 라인의 코드입니다

JPanel panel = new JPanel() { 
    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g) 
     g.drawLine(x1, y1, x2, y2); 
    } 
} 

. 당신은 단지 버튼을 누른 후 그것이 당신의 메인 클래스에서, 글로벌 boolean 변수를 생성하고, 버튼을 누를 때, 당신은 당신의 JPanel에 그렇게 만들 때 true로 설정, 선을 그리려면 :

JPanel panel = new JPanel() { 
     @Override 
     protected void paintComponent(Graphics g) { 
      if (myBoolean) { 
       super.paintComponent(g) 
       g.drawLine(x1, y1, x2, y2); 
      } 
     } 
    } 
+2

1+ 그러나 JPanel 확장 클래스의 'paintComponent (Graphics g)'오버라이드 안에 super의'paintComponent (g)'메소드를 호출하도록 OP를 상기시키는 것을 잊지 마시기 바랍니다. –

+2

오버라이드 (override)되는 메소드의 액세스 지정자를 최대한 동일하게합니다. 여기서는'protected'이며 public이 아닙니다 :-) –

+2

또한 패널의 getPreferredSize() 메소드를 오버라이드해야합니다. 그렇지 않으면 크기가 (0, 0)이 될 것이고 패널은 레이아웃 관리자가 사용 중입니다. – camickr

1

다른 답변에서 주어진 조언은 너무 좋지만 자신을 멈추게 할 수는 없지만 그림을 그리려면 같은 단어 나 두 단어를 추가하는 것에서부터 repaint()으로 전화해야합니다. 내부에서 JButton에 첨부 된 actionPerformed

이미 @camickr에 명시된대로 도면 용 확장 클래스 내에 getPreferredSize()을 사용하면 도면을 수행해야하는 유효한 스테이징 영역이 제공됩니다. 이 example도이 방향으로 도움이 될 수 있습니다.

또한, 경우에 당신은 당신이 단순히 List에 저장하고 다시 때마다 새로운 라인을 모두 그릴이 List에 반복 할 수있는, 지금까지 그대로 Board에 그려진 된 모든 라인을 유지하고 싶어 그려야한다.

import java.awt.*; 
import java.awt.event.*; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import javax.swing.*; 

public class LineExample { 

    private DrawingBoard board; 
    private JButton drawLineButton; 

    private Random random; 

    private ActionListener buttonAction = new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent ae) { 
      int width = board.getWidth(); 
      int height = board.getHeight(); 
      Line line = new Line(random.nextInt(width), 
           random.nextInt(height), 
           random.nextInt(width), 
           random.nextInt(height)); 
      board.setValues(line); 
     }  
    }; 

    public LineExample() { 
     random = new Random(); 
    } 

    private void displayGUI() { 
     JFrame frame = new JFrame("Drawing Lines Example"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     JPanel contentPane = new JPanel(new BorderLayout(5, 5)); 
     board = new DrawingBoard(400, 400); 
     contentPane.add(board, BorderLayout.CENTER); 

     drawLineButton = new JButton("LINE"); 
     drawLineButton.addActionListener(buttonAction); 
     contentPane.add(drawLineButton, BorderLayout.PAGE_END); 

     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     Runnable runnable = new Runnable() { 
      @Override 
      public void run() { 
       new LineExample().displayGUI(); 
      }  
     }; 
     EventQueue.invokeLater(runnable); 
    } 
} 

class DrawingBoard extends JPanel { 

    private int width; 
    private int height; 

    private List<Line> lines; 

    public DrawingBoard(int w, int h) { 
     width = w; 
     height = h; 
     lines = new ArrayList<Line>(); 
    } 

    public void setValues(Line line) { 
     lines.add(line); 
     repaint(); 
    } 

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

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     for (Line line : lines) { 
      int xs = line.getXStart(); 
      int ys = line.getYStart(); 
      int xe = line.getXEnd(); 
      int ye = line.getYEnd(); 
      g.drawLine(xs, ys, xe, ye); 
     } 
    }  
} 

class Line { 

    private Point startPoint; 
    private Point endPoint; 

    public Line(int xs, int ys, int xe, int ye) { 
     startPoint = new Point(xs, ys); 
     endPoint = new Point(xe, ye); 
    } 

    public int getXStart() { 
     return startPoint.getX(); 
    } 

    public int getYStart() { 
     return startPoint.getY(); 
    } 

    public int getXEnd() { 
     return endPoint.getX(); 
    } 

    public int getYEnd() { 
     return endPoint.getY(); 
    } 
} 

class Point { 

    private int x; 
    private int y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public int getX() { 
     return x; 
    } 

    public int getY() { 
     return y; 
    } 
}