我怎样才能在中间设置?

S S*_*lin 2 java center draw

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

Mad*_*mer 7

没有任何其他证据,我你已经覆盖了paint类似a 的方法,JFrame并直接绘制它.

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

在此输入图像描述

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

相反,你应该画在框架的内容区域上.

在此输入图像描述

现在,矩形看起来正确居中.在我的测试,我的第一帧(坏)设置为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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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