0

当我运行这个类时,它会在框架的北中心打印图形,我不知道如何将它居中。我尝试以多种不同的方式调整 x 值,并注意到抛物线在正确的区域移动。

class FunctionPlotPanel extends JPanel
{
   protected void paintComponent(Graphics g){
   super.paintComponent(g);

   int x1=0;
   int y1=100;
   int x2=200;
   int y2=100;
   g.drawLine( x1, y1, x2, y2);

   int x11=100;
   int y11=0;
   int x22=100;
   int y22=200;
   g.drawLine(x11, y11, x22, y22);

   Polygon p = new Polygon();

   double scalefactor = 0.1;
   for(int x=-100;x<=100;x++)
   {
      p.addPoint(x+100,100-(int)(scalefactor*x*x));
   }

   int[] xPoints=p.xpoints;
   int[] yPoints=p.ypoints;

   int nPoints=p.npoints;

   g.drawPolyline(xPoints,yPoints,nPoints);
  }
 }
4

1 回答 1

1

中心位置是可视空间与图表大小之间的差异。

使用getWidthand getHeightof you 组件来确定当前的可视区域并计算从左上角到你需要的像素数...

在可能的情况下,不要依赖幻数

在此处输入图像描述

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class CenterGraphics {

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

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

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

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

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int x = (getWidth() - 100) / 2;
            int y = (getHeight() - 100) / 2;
            g2d.drawRect(x, y, 100, 100);
            g2d.dispose();
        }

    }

}
于 2013-11-08T20:34:40.323 回答