java 如何创建用于绘制多边形的图形对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17535046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:14:34  来源:igfitidea点击:

How to create Graphics object for drawing Polygon?

javagraphicsdrawingpolygonjava-2d

提问by nazar_art

I need to draw a Polygon - by connecting consecutive points and then connecting the last point to the first.

我需要绘制一个多边形 - 通过连接连续的点,然后将最后一个点连接到第一个点。

With this goal I tried to use drawPolygon(xPoints, yPoints, nPoints). To my mind it's much more convenience approach to achieve this aim

为了这个目标,我尝试使用drawPolygon(xPoints, yPoints, nPoints)。在我看来,实现这一目标更方便

But the Graphicsclass is abstract class and I we can't create instance object and call drawPolygon()method?

但是这个Graphics类是抽象类,我不能创建实例对象和调用drawPolygon()方法?

Code:

代码:

public void draw() {
        Graphics g = null;
        int xPoints [] = new int[pointsList.size()];
        int yPoints [] = new int[pointsList.size()];
        int nPoints = pointsList.size();

        for (int i = 0; i < pointsList.size(); i++) {
            xPoints [i] = (int) pointsList.get(i).getX();
            yPoints [i] = (int) pointsList.get(i).getY();
        } 

        g.drawPolygon(xPoints, yPoints, nPoints);
    }
  • Can we circumvent calling this method at any way?
  • Maybe exist some other ways to achieve this aim?
  • 我们可以以任何方式绕过调用这个方法吗?
  • 也许存在其他一些方法来实现这个目标?

回答by Isaac

The reason the developers made Graphics abstract was that a graphics object needs to come from somewhere. For instance a JPanel or JFrame object have a graphics object associated with them since they render viewable areas to the screen. A graphics object is usually assigned with the getGraphics() method. Here is a quick example:

开发人员将 Graphics 抽象化的原因是图形对象需要来自某个地方。例如,JPanel 或 JFrame 对象有一个与之关联的图形对象,因为它们将可视区域呈现到屏幕上。图形对象通常使用 getGraphics() 方法分配。这是一个快速示例:

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

    public class Polygon extends JFrame {
        public static void main(String args[]){
            Test a = new Test();
            a.drawAPolygon();
        }


        public Polygon(){
            setSize(300,300);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }

        void drawAPolygon(int[] xPoints, int[] yPoints, int numPoints){
            Graphics g = getGraphics();
            g.drawPolygon(xPoints, yPoints, numPoints);
        }
        //@override
            public void paint(Graphics g){
            super.paint(g);
            //could also do painting in here.
        }
    }

回答by ChrisMcJava

I have had the same problem, this was how I circumvented it:

我遇到了同样的问题,这就是我规避它的方式:

//assuming you are displaying your polygon in a JFrame with a JPanel
public class SomeDrawingFrame extends JPanel{
    SomeDrawingFrame(){
    }

    @Override   //JFrame has this method that must be overwritten in order to 
                  display a rendered drawing.

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Polygon square = new Polygon();

        // these points will draw a square
        square.addPoint((0, 0));    //use this.getWidth() method if you want to 
                                         create based on screen size
        square.addPoint((0, 100));
        square.addPoint((100, 100));
        square.addPoint((100, 0)); 
        int y1Points[] = {0, 0, 100, 100};

        g.draw(polygon);
    }
}

now just create an instance of this and add it to a JFrame of minimum height and width of 100 each. You can use JFrame's getWidth() method which will return the size of the JFrame and use this to set your points instead (which is better) because then the image will render relative to the size of the frame itself.

现在只需创建一个实例并将其添加到最小高度和宽度为 100 的 JFrame 中。您可以使用 JFrame 的 getWidth() 方法,该方法将返回 JFrame 的大小并使用它来设置您的点(更好),因为这样图像将相对于框架本身的大小呈现。

回答by MadProgrammer

Painting is controlled by the RepaintManager. Painting in Swing is done via a series of methods which are called on your behalf when the RepaintManagerdecides your component needs to be update (you can, of course, request repaints, but the RepaintManagerwill decided when, what and how much).

绘画由RepaintManager. 在 Swing 中绘制是通过一系列方法完成的,当RepaintManager您决定需要更新组件时,这些方法会代表您调用(当然,您可以请求重绘,但RepaintManager将决定何时、什么和多少)。

In order to perform custom painting in Swing, you need to override one of the methods that are called as part of the paint cycle.

为了在 Swing 中执行自定义绘制,您需要覆盖作为绘制周期一部分调用的方法之一。

It is recommendedthat you override paintComponent

建议你重写paintComponent

You can check out

你可以退房

For more details.

更多细节。

In your example, your Graphicsis null...Graphics g = null;which isn't going to help...

在你的例子中,你Graphicsnull......Graphics g = null;这不会有帮助......

enter image description here

在此处输入图片说明

import java.awt.BorderLayout;
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 SimplePloy {

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

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

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

    public class PloyPane extends JPanel {

        private int[] xPoints;
        private int[] yPoints;

        public PloyPane() {
        }

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

        @Override
        public void invalidate() {

            xPoints = null;
            yPoints = null;

            super.invalidate(); 
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (xPoints == null || yPoints == null) {

                int width = getWidth() - 1;
                int height = getHeight() - 1;

                int halfWidth = width / 2;
                int halfHeight = height / 2;
                int innerWidth = width / 8;
                int innerHeight = height / 8;

                xPoints = new int[9];
                yPoints = new int[9];

                xPoints[0] = halfWidth;
                yPoints[0] = 0;

                xPoints[1] = halfWidth - innerWidth;
                yPoints[1] = halfHeight - innerHeight;  

                xPoints[2] = 0;
                yPoints[2] = halfHeight;

                xPoints[3] = halfWidth - innerWidth;
                yPoints[3] = halfHeight + innerHeight;  

                xPoints[4] = halfWidth;
                yPoints[4] = height;

                xPoints[5] = halfWidth + innerWidth;
                yPoints[5] = halfHeight + innerHeight;  

                xPoints[6] = width;
                yPoints[6] = halfHeight;

                xPoints[7] = halfWidth + innerWidth;
                yPoints[7] = halfHeight - innerHeight;  

                xPoints[8] = halfWidth;
                yPoints[8] = 0;  

            }
            g2d.drawPolygon(xPoints, yPoints, xPoints.length);
            g2d.dispose();
        }

    }

}