2016-07-19 2 views
0

jframe의 가운데에 사각형을 만들려고합니다. 나는 인세 트로 노력했지만 나는 어떤 행운도 없었다.JFrame에서 사각형 중심 지정

public class RectDraw extends JComponent{ 

    Shape rect; 
    public void paint(Graphics g){ 
     Graphics2D graph2 = (Graphics2D)g; 
     graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
       RenderingHints.VALUE_ANTIALIAS_ON); 
     rect = new Rectangle2D.Float(50,50,15,15); 


     graph2.setPaint(Color.BLACK); 
     graph2.fill(rect); 
     graph2.draw(rect); 

    } 


} 

주 : 나는 구형 다음 클래스를 만든

public class TheMain{ 


    public static void main(String[] args) { 

     Screen screen = new Screen(); 
     RectDraw rect = new RectDraw(); 
     screen.add(rect, BorderLayout.CENTER); 

} 

그리고 이것은 클래스 화면입니다 : 내가하기 위해 변경해야하는지 그래서

public class Screen extends JFrame{ 


    public Screen(){ 
     this.setSize(500, 500); 
     this.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     this.setLocationRelativeTo(null); 
     this.setResizable(false); 
     this.setTitle("Testing"); 
     this.getContentPane().setBackground(Color.GRAY); 
     this.setVisible(true); 

    } 
} 

이 사각형을 jframe의 중앙에 배치 하시겠습니까?

감사합니다.

+3

'Rectangle2D'의'x '값으로 사용되는'(getWidth() - width)/2'는'width '가 사각형의 너비로 사용되는 경우 사각형을 가로로 가운데 맞춤합니다. 높이 맞추는 방법에 대해 어떻게 생각하세요? –

답변

-1

ScreenpaintComponent 메소드를 재정의해야합니다.

너의 직사각형 너비는 50 높이 100이다. 간단히 몇 가지 수학을해라.

@Override 
public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    Graphics2D graph2 = (Graphics2D)g; 
    //To center the rectangle, we need to specify the center x,y points on the frame 
    //Divide width and height into two, and minus the width and height of the rectangle 
    graph2.drawRect(getWidth()/2 - 50/2, getHeight()/2 - 100/2, 50, 100); 
} 
+2

(1-)'화면을 통과해야합니다. '- 그렇지 않습니다. 컴퍼넌트의'getWidth()'및'getHeight()'메소드를 사용해, 컴퍼넌트의 사이즈를 취득 할뿐입니다. 그렇다면 당신은 당신의 수학을합니다. 또한 paint()가 아닌'paintComponent()'를 오버라이드해야합니다. – camickr

관련 문제