我怎样才能在中间设置?

时间:2012-12-05 22:59:19

标签: java draw center

我尝试在Java中绘制一个矩形。我设置了帧大小(800,400)和可调整大小(假)矩形的x = 50,y = 50宽度= 700高度= 300.为什么它不在中间?谢谢。

2 个答案:

答案 0 :(得分:7)

如果没有任何其他证据,我会猜测你已经覆盖了像paint这样的JFrame方法并直接绘制它。

问题是,框架有装饰(例如边框和标题栏),占据了内部空间框架......

enter image description here

从技术上讲,这是正确的。矩形被画在画框的中央,但由于画框的装饰,它看起来有点高......

相反,你应该画在画面的内容区域上。

enter image description here

此处矩形现在看起来正确居中。在我的测试中,我将第一帧(坏)设置为800x400,我将第二帧的内容窗格的首选大小设置为800x400,这使得帧大小实际为816x438,因为帧的装饰现在是之外油漆区。

public class CenterOfFrame {

    public static void main(String[] args) {
        new CenterOfFrame();
    }

    public CenterOfFrame() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                new BadFrame().setVisible(true);

                JFrame goodFrame = new JFrame();
                goodFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                goodFrame.setContentPane(new PaintablePane());
                goodFrame.pack();
                goodFrame.setLocationRelativeTo(null);
                goodFrame.setVisible(true);

            }
        });
    }

    public class BadFrame extends JFrame {

        public BadFrame() {
            setSize(800, 400);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            paintTest(g, getWidth() - 1, getHeight() - 1);
        }
    }

    public void paintTest(Graphics g, int width, int height) {
        g.setColor(Color.RED);
        g.drawLine(0, 0, width, height);
        g.drawLine(width, 0, 0, height);
        g.drawRect(50, 50, width - 100, height - 100);
    }

    public class PaintablePane extends JPanel {

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

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
            paintTest(g, getWidth() - 1, getHeight() - 1);
        }
    }
}

这是众多原因之一,为什么你不应该覆盖顶级容器的paint方法;)

答案 1 :(得分:0)

    Rectangle rect = new Rectangle(50,50,700,300); 

这应该可以正常工作,你是否在访问成员变量之前创建一个新的Rectangle实例?

800乘400也是一种奇怪的分辨率,800乘600更为标准。