本文介绍了在jframe中创建java的正方形,矩形,三角形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是代码:我有一个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();

$ / code>

如何创建 JFrame 三角形,正方形和矩形?谢谢

解决方案

在我开始写我的答案之前,我需要鼓励你仔细阅读:如何创建一个有效的

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

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

public class ShapesDrawing {

private JFrame frame;
私有JPanel窗格;

public 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); //总是先调用这个方法!
g.drawRect(10,10,50,50); //绘制平方
g.drawRect(10,75,100,50); //绘制矩形
g.drawPolygon(new int [] {35,10,60},new int [] {150,200,200},3); //绘制三角形
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);


$ / code $ / pre

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

如果你需要填充形状,然后调用 fillRect fillPolygon 而不是 drawRect drawPolygon

  @Override 
保护void paintComponent(Graphics g){
super.paintComponent(g); //总是先调用这个方法!
g.drawRect(10,10,50,50); //绘制正方形
g.fillRect(150,10,50,50); //填充一个正方形
g.drawRect(10,75,100,50); //绘制矩形
g.fillRect(150,70,100,50); //填充一个正方形
g.drawPolygon(new int [] {35,10,60},new int [] {150,200,200},3); //绘制三角形
g.fillPolygon(new int [] {185,150,215},new int [] {150,200,200},3); //填充三角形
g.dispose();
}





编辑



根据@ MadProgrammer的评论:

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

  @Override 
protected void paintComponent(Graphics g){
super.paintComponent (G); //总是先调用这个方法!

Graphics2D g2d =(Graphics2D)g;
g2d.draw(新的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();
}

产生以下输出:




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?

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 JFrame the triangle, square and rectangle? correct my code thanks

解决方案

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 Example and a Short, Self Contained, Correct Example.


  1. From your (now deleted) code, I see you haven't gone through the Swing Tutorial on Custom Painting yet 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 static modifier will harm you, static isn'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 essentials before 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 JFrame or override your component's getPreferredSize().

  6. On your deleted code, you had a MouseListener attached to a JButton, instead you need to use an ActionListener, see How to use Actions to 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 main method 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.


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:

  • A rectangle has a width and a height, both are different
  • The way to draw a rectangle in Swing is with draw(Shape) of the Graphics2D method where Shape would be an instance of Rectangle2D

To draw a square we need to know that:

  • A square has a width and a height, both are equal size
  • The way to draw a square in Swing is with draw(Shape) of the Graphics2D method where Shape would be an instance of Rectangle2D

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 width and height equal size for the square and different size for the rectangle.

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 drawTriangle in Swing, but we have 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

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

@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 JFrame will be smaller than what we want, so it should look like this:

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

Don't forget to call @Override in those methods!

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:

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 fillRect and fillPolygon instead of drawRect and 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();
}

Edit

As per @MadProgrammer's comment:

Here's the updated paintComponent method using the 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:

这篇关于在jframe中创建java的正方形,矩形,三角形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:50