简体   繁体   English

在 Java 中绘制矩形

[英]Drawing Rectangle in Java

I am trying to draw a rectangle.我正在尝试绘制一个矩形。 But I am not sure how, it paints in certain panel.但我不确定如何,它在某些面板上绘制。 Would like to see an example for, How I can supply the panel and position for drawing the rectangle.想看一个示例,我如何提供用于绘制矩形的面板和位置。 I have the following template, I would like to see what modifications I need to make to use this class to draw rectangle on any Panels.我有以下模板,我想看看我需要做哪些修改才能使用此类在任何面板上绘制矩形。 My intention is to use panels width, and heights and add a rectangle to that position.我的目的是使用面板宽度和高度,并在该位置添加一个矩形。 Goal is to be able to use this class any where with any JPanels.目标是能够在任何 JPanels 的任何地方使用此类。

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

public class DrawRectangle{

    private int startX;
    private int startY;
    private int width;
    private int height;
    private Color color;
    private JPanel panel;

    public DrawRectangle(JPanel panel, int startX, int startY, int width, int height, Color color) {
        this.startX = startX;
        this.startY = startY;
        this.width = width;
        this.height = height;
        this.color = color;
            this.panel = panel; 
    }

    public void paint(Graphics g) {
        g.setColor(this.color);
        g.fillRect(this.startX, this.startY, this.width, this.height);
        g.drawRect(this.startX, this.startY, this.width, this.height);
    }
}

You would have to modify the JPanel of interest in order to use that code by:您必须修改感兴趣的 JPanel 才能通过以下方式使用该代码:

  • Overriding its paintComponent method覆盖其paintComponent方法
  • First calling the super's paintComponent method in your override首先在覆盖中调用 super 的paintComponent 方法
  • And then drawing your own DrawRectangle class's paint method然后绘制自己的DrawRectangle类的paint方法
  • If you want to be able to draw multiple rectangles, then give the JPanel a List<DrawRectangle> and draw those in a for loop within paintComponent如果您希望能够绘制多个矩形,则为 JPanel 提供一个List<DrawRectangle>并在paintComponent 内的 for 循环中绘制它们

For example, for one rectangle:例如,对于一个矩形:

public class DrawingPanel extends JPanel {
    private DrawRectangle drawRectangle;

    public DrawingPanel(DrawRectangle drawRectangle) {
        this.drawRectangle = drawRectangle;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (drawRectangle != null) {
            drawRectangle.paint(g);
        }
    }
}

and for many rectangles:对于许多矩形:

public class DrawingManyRectPanel extends JPanel {
    private List<DrawRectangle> drawRectangles;

    public DrawingManyRectPanel(List<DrawRectangle> drawRectangles) {
        this.drawRectangles = drawRectangles;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (drawRectangles != null) {
            for (DrawRectangle rectangle : drawRectangles) {
                rectangle.paint(g);
            }
        }
    }
}

In these classes, the constructor is overridden to allow injection of rectangles into the class via constructor call.在这些类中,构造函数被覆盖以允许通过构造函数调用将矩形注入到类中。 For the second class, I'd also add a method that allows addition of further rectangles:对于第二个类,我还将添加一个允许添加更多矩形的方法:

public void addRectangle(DrawRectangle rectangle) {
    drawRectangles.add(rectangle);
    repaint();
}

similar for removing rectangles类似于删除矩形


An alternate way to do this, if you don't plan to remove rectangles or modify the ones already drawn, is to draw them in a BufferedImage, and then draw that image in the drawing JPanel's paintComponent method.如果您不打算移除矩形或修改已绘制的矩形,另一种方法是在 BufferedImage 中绘制它们,然后在绘图 JPanel 的 paintComponent 方法中绘制该图像。

Check out the Graphics2D class it is meant for exactly what you are trying to do and is better suited for drawing than the regular paintComponent method.查看 Graphics2D 类,它完全适用于您要执行的操作,并且比常规的paintComponent方法更适合绘图。 You can read about how to use Graphics2D here .您可以在此处阅读有关如何使用 Graphics2D 的信息

Firstly note that you cannot have a Graphics2D object without casting it from a Graphics object like I did here Graphics2D g2 = (Graphics2D) g;首先需要注意的是,你不能有一个Graphics2D对象,而不从铸造它Graphics对象,像我一样在这里Graphics2D g2 = (Graphics2D) g; . .

This is an example that should help you to get started, keep in mind I'm using absolute layout so no layout manager.这是一个应该可以帮助您入门的示例,请记住我使用的是绝对布局,因此没有布局管理器。 This is code I was using to create a blackjack game so thats why things are names are not generic.这是我用来创建二十一点游戏的代码,所以这就是名称不通用的原因。

Also I added smoothing so your shapes with Graphics2D will look really nice and the methods center the shapes on screen which will probably work well with your JPanels.我还添加了平滑功能,因此您使用 Graphics2D 的形状看起来非常好,并且这些方法将形状放在屏幕上,这可能与您的 JPanels 配合得很好。

Notice how I created specific methods for the Graphics2D objects I wanted to draw and then drew them using the Graphics class.请注意我是如何为要绘制的 Graphics2D 对象创建特定方法,然后使用 Graphics 类绘制它们的。 That seemed to work the best for me so that my paintComponent wasn't just littered with endless repeated code.这对我来说似乎是最好的,所以我的paintComponent不仅是无休止的重复代码。 frame in my code was getting the width and height of the JFrame I had the JPanel in so for you simply refer to the JPanel you would have it in instead.我的代码中的frame正在获取JFrame的宽度和高度,我将JPanel放入其中,因此您只需参考您将拥有它的JPanel

class DrawTable extends JPanel
{

    DrawTable()
    {
        super();
        System.out.println("Looks good to me pal!");
    }

    @Override
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        //Setup background
        drawRectangle(g, Color.BLACK,
                frame.getWidth() / 2, frame.getHeight() / 2,
                frame.getWidth(), frame.getHeight());

        // Create table at center
        drawRectangle(g, new Color(206, 187, 158),
                frame.getWidth() / 4, frame.getHeight(), //left table leg
                50, 600);
        drawRectangle(g, new Color(206, 187, 158),
                frame.getWidth() / 1.5, frame.getHeight(), //right table leg
                50, 600);
        drawEllipse(g, new Color(153, 154, 104),
                frame.getWidth() / 2, frame.getHeight() / 2, //Draws outer circle
                1200, 400);
        drawEllipse(g, new Color(53, 101, 77),
                frame.getWidth() / 2, frame.getHeight() / 2, //Draws inner circle
                1125, 350);
    }

    private void drawEllipse(Graphics g, Color color, double x, double y, double width, double height) //centers ellipse
    {
        Graphics2D g2 = (Graphics2D) g;
        double centerX = (double) x - width / 2;
        double centerY = (double) y - height / 2;
        Ellipse2D ellipse = new Ellipse2D.Double(centerX, centerY, width, height);
        RenderingHints render = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        render.put(
                RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHints(render);
        g2.setColor(color);
        g2.fill(ellipse);
        g2.draw(ellipse);
    }

    private void drawRectangle(Graphics g, Color color, double x, double y, double width, double height) //centers rectangle
    {
        Graphics2D g2 = (Graphics2D) g;
        double centerX = (double) x - width / 2;
        double centerY = (double) y - height / 2;
        Rectangle2D rect = new Rectangle2D.Double(centerX, centerY, width, height);
        RenderingHints render = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        render.put(
                RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g2.addRenderingHints(render);
        g2.setColor(color);
        g2.fill(rect);
    }
}

Let me know if you need anymore help!如果您需要更多帮助,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM