中心在Java框架/面板中对齐矩形

时间:2013-06-02 05:59:41

标签: java swing java-2d repaint paintcomponent

尝试使用paintComponent创建牛眼计划。我希望矩形位于屏幕的中心。我该怎么做?

1 个答案:

答案 0 :(得分:3)

基本上,你根据它的宽度和高度在组件的中心周围绘制你想要的东西

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int width = getWidth() - 1;
    int height = getHeight() - 2;
    g.drawLine(width / 2, 0, width / 2, height);
    g.drawLine(0, height / 2, width, height / 2);
}

查看Performing Custom Painting2D Graphics了解详情