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

Create the square, rectangle, triangle of java in jframe

我有一个问题 Java 据我了解无法在 Java 中绘制几何图形,代码和以下内容可以帮助我吗?

这是代码:

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();
    }

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

在我开始写我的答案之前,我需要鼓励您仔细阅读:如何创建一个有效的 Minimal, Complete and Verifiable Example and a Short, Self Contained, Correct Example.


  1. 从你的(现已删除)代码中,我看到你还没有完成 Swing Tutorial on Custom Painting 或者你甚至没有注意它,这一行会给你带来麻烦

    static Graphics2D g = new Graphics2D() 
    
  2. 过度使用 static 修饰符会伤害你,static 不是一个 cross-method 魔法词来让你的变量在你的程序的任何地方都可以访问,您应该改为创建程序的实例并从那里调用方法(它们不是静态的),请参阅 Why are static variables considered evil?, and you should really go back and learn the essentials,然后再使用 GUI 以及 Swing 自定义绘画为您的学习增加更多的复杂性。

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

    panel.setLayout(null);
    

    你真的应该考虑检查 layout managers

  4. 您正在使用已弃用的方法 JFrame#show() instead you should be using JFrame#setVisible() 方法。

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

  6. 在您删除的代码中,您将 MouseListener 附加到 JButton,而您需要使用 ActionListener,请参阅 How to use Actions学习这个。

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

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


说完上面的内容(你应该仔细阅读)我们可以继续编码部分:

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

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

你一定是在说……"But the method you're using to draw the square is the same as the rectangle!",好吧……是的,我们是,区别在于我们要通过一个widthheight 正方形大小相同,矩形大小不同。

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

  • 一个三角形有3条边,它们的大小可以相同也可以不同
  • 我们没有在 Swing 中 drawTriangle 的方法,但是我们有 drawPolygon(xPoints, yPoints, nPoints) draw(Shape) of the Graphics2D method, which will draw a Polygon of nPoints (3 in this case), taking the coords from each array element of xPoints for the X coords and yPoints for the Y coords and where Shape would be an instance of Polygon

现在,将所有这些放在一起,我们应该将所有代码放在我们的 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
}

但是我们还需要重写另一个方法getPreferredSize() on our JPanel, (see: Should I avoid the use of setPreferred|Maximum|MinimumSize in Swing?一般的共识是可以的),否则我们的JFrame会比我们想要的小,所以它应该是这样的:

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

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

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

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);
    }
}

我真的希望你能阅读我在这里 post 编辑的所有 link,因为它是值得的

如果你需要填充形状然后调用 fillRectfillPolygon 而不是 drawRectdrawPolygon:

@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();
}


编辑

根据@MadProgrammer 的评论:

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

这是更新后的 paintComponent 方法,使用形状 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();
}

产生以下输出: