java 在jframe中创建java的正方形、长方形、三角形

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41941855/
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-03 06:15:54  来源:igfitidea点击:

Create the square, rectangle, triangle of java in jframe

javaswinggraphicsgeometrycustom-painting

提问by Sasapp

I have a problem with Java As I understood not come Draw Geometric figures in Java, the code and the Following you can help me?

我的Java有问题 据我了解,用Java绘制几何图形不是来的,下面的代码能帮帮我吗?

This is the code:

这是代码:

public class Gioco {


    public static void main (String args [])
    {
        PaintRect();

    }

    public static void PaintRect() {

        g.drawRect(100,100,300,300);
        g.drawLine(100,100,100,100);
        g.setBackground(Color.BLACK);
        System.out.println("Trasut");
        credits.setText("Kitebbiv");
        credits.setBackground(null);
        credits.setEditable(false);
        credits.setFocusable(false);
        credits.setBounds(0,0,100,100);
        credits.setForeground(Color.BLACK);
        panel.add(credits);
        g.getPaint();
    }

How can I create a JFramethe triangle, square and rectangle? correct my code thanks

如何创建JFrame三角形、正方形和矩形?更正我的代码谢谢

回答by Frakcool

Before I even start writing my answer I need to encourage you to read carefully to: How to create a valid Minimal, Complete and Verifiable Exampleand a Short, Self Contained, Correct Example.

在我开始写我的答案之前,我需要鼓励您仔细阅读:如何创建一个有效的最小、完整和可验证的示例和一个简短的、自包含的、正确的示例



  1. From your (now deleted) code, I see you haven't gone through the Swing Tutorial on Custom Paintingyet or you didn't even pay attention to it, this line will cause you problems

    static Graphics2D g = new Graphics2D() 
    
  2. The excessive use of staticmodifier will harm you, staticisn't a cross-method magic word to make your variables be accessible anywhere in your program, you should instead create an instance of your program and call the methods from there (they not being static), see Why are static variables considered evil?, and you should really go back and learn the essentialsbefore adding more complexity to your learning with a GUI and even more with Swing custom painting.

  3. You're making use of setBounds()method, which suggests (and I can confirm in your deleted code) that you're using a null-layout:

    panel.setLayout(null);
    

    You should really consider checking the layout managers

  4. You're making use of a deprecated method JFrame#show()instead you should be using JFrame#setVisible()method.

  5. You're manually setting the size of your JFrame, you should instead use a layout manager and call the method JFrame#pack()which will calculate the preferred size for your JFrameor override your component's getPreferredSize().

  6. On your deleted code, you had a MouseListenerattached to a JButton, instead you need to use an ActionListener, see How to use Actionsto learn this.

  7. You're not placing your program on the Event Dispatch Thread (EDT)which could make your program to freeze, because Swing is not Thread safe. You can correct this by writing your mainmethod as follows:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Your constructor here
            }
        });
    }
    
  8. You should be more polite: "correct my code thanks"sounds like an order, I would have said that like could you help me?which sounds like a request / petition for someone to give you a hand, because they can, not because they must help you, all the above points correct your code.

  1. 从您的(现已删除)代码中,我看到您还没有完成自定义绘画Swing 教程,或者您甚至没有注意它,这一行会给您带来问题

    static Graphics2D g = new Graphics2D() 
    
  2. 过度使用static修饰符会伤害你,static不是一个跨方法的魔法词,让你的变量在你的程序中的任何地方都可以访问,你应该创建一个程序实例并从那里调用方法(它们不是静态的) ,请参阅为什么静态变量被认为是邪恶的?,并且在使用 GUI 甚至使用 Swing 自定义绘画为您的学习增加更多复杂性之前,您真的应该回去学习基础知识。

  3. 您正在使用setBounds()方法,该方法表明(并且我可以在您删除的代码中确认)您正在使用null-layout

    panel.setLayout(null);
    

    你真的应该考虑检查布局管理器

  4. 您正在使用已弃用的方法,JFrame#show()而应该使用JFrame#setVisible()方法。

  5. 你手动设置您的大小JFrame,你应该使用布局管理器调用该方法JFrame#pack()将计算首选大小为您JFrame或覆盖您的组件getPreferredSize()

  6. 在您删除的代码上,您有一个MouseListener附加到JButton,而您需要使用ActionListener,请参阅如何使用操作来了解这一点。

  7. 您没有将您的程序放在事件调度线程 (EDT) 上,这可能会使您的程序冻结,因为 Swing 不是线程安全的。您可以通过main按如下方式编写方法来纠正此问题:

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Your constructor here
            }
        });
    }
    
  8. 你应该更有礼貌:“更正我的代码,谢谢”听起来像是命令,我会说你能帮我吗?这听起来像是请求/请愿某人帮助您,因为他们可以,而不是因为他们必须帮助您,以上所有要点都可以更正您的代码。



After all the above has being said (and which you should read carefully) we can continue to the coding part:

说完以上所有内容(您应该仔细阅读),我们可以继续编码部分:

In order to draw a rectangle we need to learn something about a rectangle:

为了绘制矩形,我们需要了解有关矩形的知识:

To draw a square we need to know that:

要绘制正方形,我们需要知道:

You must be saying... "But the method you're using to draw the square is the same as the rectangle!", well... yep, we are, the difference lies in that we're going to pass a widthand heightequal size for the square and different size for the rectangle.

您一定是在说…… “但是您用来绘制正方形的方法与绘制矩形的方法相同!” ,嗯...是的,我们是,不同之处在于我们将传递 awidthheight相同大小的正方形和不同大小的矩形。

To draw a triangle you need to know that:

要绘制三角形,您需要知道:

  • A triangle has 3 sides, they can be same or different sizes
  • We have no method to drawTrianglein Swing, but we have drawPolygon(xPoints, yPoints, nPoints)draw(Shape)of the Graphics2Dmethod, which will draw a Polygon of nPoints(3 in this case), taking the coords from each array element of xPointsfor the Xcoords and yPointsfor the Ycoords and where Shapewould be an instance of Polygon
  • 一个三角形有3条边,它们的大小可以相同也可以不同
  • 我们没有方法drawTriangle在Swing,但我们有所述的方法,其中将绘制的多边形(在本例3)中,从每个阵元取COORDS为COORDS和用于COORDS并且其中将是一个实例drawPolygon(xPoints, yPoints, nPoints)draw(Shape)Graphics2DnPointsxPointsXyPointsYShapePolygon

Now, putting all that together we should have all that code in an overridden method of our JPanelcalled paintComponent()as shown in the tutorial (See point #1). It should look like this:

现在,将所有这些放在一起,我们应该将所有代码放在我们JPanel调用的重写方法中paintComponent(),如教程中所示(参见第 1 点)。它应该是这样的:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //ALWAYS call this method first!
    g.drawRect(10, 10, 50, 50); //Draws square
    g.drawRect(10, 75, 100, 50); //Draws rectangle
    g.drawPolygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3); //Draws triangle
}

But we also need to override another method getPreferredSize()on our JPanel, (see: Should I avoid the use of setPreferred|Maximum|MinimumSize in Swing?the general consensus says yes), otherwise our JFramewill be smaller than what we want, so it should look like this:

但是我们还需要getPreferredSize()在我们的JPanel,上覆盖另一个方法(参见:我应该避免在 Swing 中使用 setPreferred|Maximum|MinimumSize 吗?普遍的共识是肯定的),否则我们的JFrame将比我们想要的小,所以它应该看起来像这:

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

Don't forget to call @Overridein those methods!

不要忘记调用@Override这些方法!

With only those methods we have completed our program to draw the shapes, but I know that if I don't post the whole code you'll end up writing the above methods in a place that won't work or cause you compilation errors, so the whole code (which in fact is a MCVE or SSCCE (see the very first paragraph in this answer to see what each means)) that produces the below output is:

仅使用这些方法,我们就完成了绘制形状的程序,但我知道如果我不发布整个代码,您最终会在无法工作或导致编译错误的地方编写上述方法,因此,产生以下输出的整个代码(实际上是 MCVE 或 SSCCE(请参阅此答案中的第一段以了解各自的含义))是:

enter image description here

在此处输入图片说明

import java.awt.Dimension;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ShapesDrawing {

    private JFrame frame;
    private JPanel pane;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ShapesDrawing().createAndShowGui();
            }
        });
    }

    public void createAndShowGui() {
        frame = new JFrame(getClass().getSimpleName());
        pane = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g); //ALWAYS call this method first!
                g.drawRect(10, 10, 50, 50); //Draws square
                g.drawRect(10, 75, 100, 50); //Draws rectangle
                g.drawPolygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3); //Draws triangle
                g.dispose();
            }

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

        frame.add(pane);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

I really hope you read every link I posted here, because it's worth it

我真的希望你阅读我在这里发布的每个链接,因为它是值得的

And if you need to fill the shapes then call fillRectand fillPolygoninstead of drawRectand drawPolygon:

如果您需要填充形状,则调用fillRectandfillPolygon而不是drawRectand drawPolygon

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //ALWAYS call this method first!
    g.drawRect(10, 10, 50, 50); //Draws square
    g.fillRect(150, 10, 50, 50); //Fills a square
    g.drawRect(10, 75, 100, 50); //Draws rectangle
    g.fillRect(150, 70, 100, 50); //Fills a square
    g.drawPolygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3); //Draws triangle
    g.fillPolygon(new int[] {185, 150, 215}, new int[] {150, 200, 200}, 3); //Fills triangle
    g.dispose();
}

enter image description here

在此处输入图片说明



Edit

编辑

As per @MadProgrammer's comment:

根据@MadProgrammer 的评论:

Could we avoid using draw/fillPolygonin favor of using the updated Shapes API ... provides much more functionality and is generally easier to use :P

我们可以避免使用draw/fillPolygon更新的 Shapes API 吗...提供了更多的功能并且通常更易于使用:P

Here's the updated paintComponentmethod using the Shapes API:

这是paintComponent使用 Shapes API的更新方法:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g); //ALWAYS call this method first!

    Graphics2D g2d = (Graphics2D) g;
    g2d.draw(new Rectangle2D.Double(10, 10, 50, 50));
    g2d.fill(new Rectangle2D.Double(150, 10, 50, 50));

    g2d.draw(new Rectangle2D.Double(10, 75, 100, 50));
    g2d.fill(new Rectangle2D.Double(150, 75, 100, 50));

    g2d.draw(new Polygon(new int[] {35, 10, 60}, new int[] {150, 200, 200}, 3));
    g2d.fill(new Polygon(new int[] {185, 150, 215}, new int[] {150, 200, 200}, 3));

    g2d.dispose();
    g.dispose();
}

Which produces the following output:

产生以下输出:

enter image description here

在此处输入图片说明