Java 构造矩形

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

Constructing Rectangle

java

提问by S.Dovra

I am constructing a Rectangleclass. I tried many times and watched numerous tutorials, but my program is not working. This is my code so far:

我正在构建一个Rectangle类。我试了很多次,看了很多教程,但我的程序不起作用。到目前为止,这是我的代码:

public class Rectangle {

    public static void main(String[] args) {

        Rectangle box = new Rectangle(5,10,20,30){
            System.out.println(new Rectangle());}
}

采纳答案by Austin

There's a few things that needs to be pointed out. First off, your code won't compile. Try this.

有几件事需要指出。首先,您的代码将无法编译。尝试这个。

import java.awt.Rectangle;

public class RectangleExample {

    public static void main(String[] args) {
        Rectangle box= new Rectangle(5,10,20,30);
        System.out.println(box);
    } 
}

You need a ;semicolon at the end of the Rectangle line instead of a bracket {. Also, it will be a good idea to rename your class to something different than Rectangle to prevent some compatibility issues for when you want to call on the Rectangleclass. Also, when you are printing out the rectangle, you want to use the box reference instead of constructing a new Rectangle.

您需要;在 Rectangle 行的末尾使用分号而不是括号{。此外,最好将您的类重命名为与 Rectangle 不同的名称,以防止在您想要调用Rectangle该类时出现一些兼容性问题。此外,当您打印矩形时,您希望使用框引用而不是构造一个新的矩形。

2nd, this won't draw a rectangle on your screen or in a window, this will only print out Rectangles toStringmethod. Which according to the javadocwill only print out a String representing this Rectangle object's coordinate and size values..

2、这不会在你的屏幕或窗口中绘制一个矩形,这只会打印出 RectanglestoString方法。其中根据javadoc只会打印出a String representing this Rectangle object's coordinate and size values..

If you want to actually draw a rectangle, you need to look into something like a JFrame or looking into paint, with something similar to this http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/DrawRectangle.htm

如果要实际绘制矩形,则需要查看 JFrame 之类的内容或查看paint类似于http://www.java2s.com/Tutorial/Java/0261__2D-Graphics/DrawRectangle.htm 的内容

回答by Kanad Jadhav

import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JFrame;

class MyCanvas extends JComponent {

    public void paint(Graphics g) {

        g.drawRect (10, 10, 200, 200);
    }
}

public class Rectangle {

    public static void main(String[] a) {

        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setBounds(30, 30, 300, 300);
        window.getContentPane().add(new MyCanvas());
        window.setVisible(true);
    }
}

回答by Shotgun Ninja

Assumptions

假设

I'm assuming you're unfamiliar with the syntax of the Java language, and trying to piece together your first Java class.

我假设您不熟悉 Java 语言的语法,并试图拼凑出您的第一个 Java 类。

I'm also assuming you need the following things:

我还假设您需要以下内容:

  1. A definition of a Rectangle.
  2. The properties xand y, indicating the Rectangle's origin.
  3. The properties widthand height, indicating the Rectangle's dimensions.
  4. The ability to create a Rectangleby specifying these four key properties.
  5. The ability to display the properties of an existing Rectangle.
  1. 的定义Rectangle
  2. 属性xy,表示Rectangle的来源。
  3. 属性widthheight,表示Rectangle的尺寸。
  4. Rectangle通过指定这四个关键属性来创建一个的能力。
  5. 显示现有Rectangle.

What You Have Already

你已经拥有的

Right now, you have a good start on this, but it's a little crossed.

现在,您在这方面有一个良好的开端,但有点过头了。

Your first and last lines:

你的第一行和最后一行:

public class Rectangle {

}

define your Rectangle class. This serves as a unit of code, and a template for making objects. Classes have defined methods (behavior) and fields/properties (information), which serve to indicate how objects of that class can operate and describe what data is accessible on each object.

定义你的 Rectangle 类。这用作代码单元和用于制作对象的模板。类定义了方法(行为)和字段/属性(信息),用于指示该类的对象如何操作并描述每个对象上可以访问哪些数据。

In short, this defines a general type of thing that can be created; in your case, you're defining what it means for an object to be a Rectanglein your code.

简而言之,这定义了可以创建的一般事物类型;在你的情况下,你正在定义一个对象Rectangle在你的代码中意味着什么。

Your second line, and its follow-up:

您的第二行及其后续行动:

public static void main(String[] args) {

}

defines a static method called main. There's a lot of stuff here to explain, but for now, just think of this as an entry pointinto a Java program. If you were to run this class as a Java program, this method would be (almost) the first code which is run.

定义了一个名为 的静态方法main。这里有很多东西要解释,但现在,只需将其视为Java 程序的入口点。如果您将此类作为 Java 程序运行,则此方法将(几乎)是运行的第一个代码。

The next line:

下一行:

Rectangle box = new Rectangle(5,10,20,30);   // notice the correction here, no curly braces, but a semicolon to end the line of code.

is what you would do to declarea Rectangle named box, then createa new Rectangle object and assign the object to the variable named box. In other words, you're making a new Rectanglewhose name is box.

就是声明一个名为 的 Rectangle box,然后创建一个新的 Rectangle 对象并将该对象分配给名为 的变量box。换句话说,您正在创建一个Rectangle名为box.

The keyword newmeans that you're making a new object of type Rectangle. The numbers in the parentheses are arguments, which define some things about the object being created. These get passed into a constructormethod of the Rectangleclass, which puts those arguments into the newly-created object.

关键字new意味着您正在创建一个类型为 的新对象Rectangle。括号中的数字是arguments,它定义了有关正在创建的对象的一些内容。这些被传递到类的构造函数方法中Rectangle,该方法将这些参数放入新创建的对象中。

Right now, though, there is no constructor, so your code won't work right in that regard. I'll write one up further down, so keep reading.

但是,现在没有构造函数,因此您的代码在这方面无法正常工作。我会再往下写一个,所以请继续阅读。

The next line:

下一行:

System.out.println(new Rectangle())  // NOTE: This is incorrect, see below

is also a little complicated. Basically, the System.out.printlnmethod writes text to the program's console, where it is seen by the user. It's used for writing out messages from your program, or showing the contents of variables in the program, to the screen.

也有点复杂。基本上,该System.out.println方法将文本写入程序的控制台,供用户查看。它用于从程序中写出消息,或将程序中变量的内容显示到屏幕上。

Right now, you're passing it a new Rectangleobject, which doesn't really make sense. A Rectangleisn't text, nor is it a basic variable (like an integer, a byte, a decimal number, a single character of text, or a true/false value), so if you try to print that new Rectangle object to the screen, you'll see some gobbledy-gook text provided by Java that looks like this:

现在,您正在向它传递一个新Rectangle对象,这实际上没有意义。ARectangle不是文本,也不是基本变量(如整数、字节、十进制数、文本的单个字符或真/假值),因此如果您尝试将新的 Rectangle 对象打印到屏幕上,你会看到一些 Java 提供的 gobbledy-gook 文本,如下所示:

Rectangle@1a2fc866

However, we have a nifty little feature that lets us tell Java how to convert objects of a specific class into a string of text; I'll show you that below.

但是,我们有一个漂亮的小功能,可以告诉 Java 如何将特定类的对象转换为文本字符串;我会在下面告诉你。

What Needs To Be Done

需要做什么

First of all, we need to have our Rectangle class.

首先,我们需要有我们的 Rectangle 类。

public class Rectangle {

}

There! We've defined a Rectangle class, for making Rectangle objects. Now, it needs some properties. We'll say these are integer numbers, called x, y, width, and height. Our class now looks like this:

那里!我们已经定义了一个 Rectangle 类,用于制作 Rectangle 对象。现在,它需要一些属性。我们会说这些都是整数,叫xywidth,和height。我们的类现在看起来像这样:

public class Rectangle {
    public int x; // Defined with a scope (public), a type (int), and a name (x).
    public int y;
    public int width, height; // We can do multiple on the same line, if they share the same scope and type.
}

Okay, cool. Now, how do we make a Rectangle? Use a constructor method! If we didn't need information about the Rectanglewhen we make a new one, we can leave this out and use a default constructorwhich Java provides for us, but we do need the information about the rectangle's position, width, and height. Our code grows to this:

好吧,爽。现在,我们如何制作一个Rectangle?使用构造函数方法!如果我们不需要有关Rectangle何时创建新矩形的信息,我们可以将其省略并使用Java 为我们提供的默认构造函数,但我们确实需要有关矩形位置、宽度和高度的信息。我们的代码长成这样:

public class Rectangle {
    public int x;
    public int y;
    public int width, height;

    // This line defines a constructor with 4 parameters: x, y, w, and h.
    public Rectangle(int x, int y, int w, int h) {
        // This initializes our x, y, width, and height properties to what is passed in.
        this.x = x;    // We set our current object's x property to the x we're given.
        this.y = y;    // We have to specify which y is which, so we use this.y to indicate the current object, and y to specify the parameter we're given.
        width = w;     // We can leave off the "this" part if there's nothing else named "width" visible in the method.
        height = h;
    }
}

Now we have the ability to make a Rectangleobject and specify its position, width, and height. But we have no program, since there is no entry point. Let's add one like you did originally, but fix some of the issues your original code had:

现在我们可以创建一个Rectangle对象并指定它的位置、宽度和高度。但是我们没有程序,因为没有入口点。让我们像最初一样添加一个,但修复原始代码的一些问题:

public class Rectangle {
    public int x;
    public int y;
    public int width, height;

    public Rectangle(int x, int y, int w, int h) {
        this.x = x;
        this.y = y;
        width = w;
        height = h;
    }

    // This is our program's entry point. It's static, and belongs to the Rectangle class, and NOT to the Rectangle objects.
    public static void main(String[] args) {
        // Inside our main method, let's make a new rectangle object.
        // Based on our constructor, the position is {5, 10}, the width is 20, and the height is 30.
        Rectangle box = new Rectangle(5, 10, 20, 30);

        // Now that it's created and named "box", let's print it out!
        // We pass the box variable as an argument to System.out.println,
        // and that method prints the box as if it were a string.
        System.out.println(box);
    }
}

We now have an entry point to our program, that does a little bit of stuff. We create a Rectangle, which we assign to the Rectangle variable called box. Then, we try to print boxas a string to the console window. As mentioned earlier, if we run the program right now, we will end up with console output like this:

我们现在有一个进入我们程序的入口点,它做了一些事情。我们创建了一个 Rectangle,并将其分配给名为 的 Rectangle 变量box。然后,我们尝试将box字符串作为字符串打印到控制台窗口。如前所述,如果我们现在运行程序,我们最终会得到如下控制台输出:

Rectangle@1a2fc866

This isn't what we want; we want to see what the Rectangle's position, height and width are! So, let's change how Java turns our Rectangle objects into strings of text, by adding a toString()method. Our Rectangle class now looks like this:

这不是我们想要的;我们想看看矩形的位置、高度和宽度是多少!因此,让我们通过添加一个toString()方法来改变 Java 将我们的 Rectangle 对象转换为文本字符串的方式。我们的 Rectangle 类现在看起来像这样:

public class Rectangle {
    public int x;
    public int y;
    public int width, height;

    public Rectangle(int x, int y, int w, int h) {
        this.x = x;
        this.y = y;
        width = w;
        height = h;
    }

    public static void main(String[] args) {
        Rectangle box = new Rectangle(5, 10, 20, 30);
        System.out.println(box);
    }

    // Here is our toString method.
    // It's declared as an @Override, which means it overrides the toString method provided by the class that Rectangle is based on (in this case, java.lang.Object).
    // The method is in the public scope, returns a String-type value, and is called toString. It doesn't have parameters, so it gets empty parentheses.
    @Override
    public String toString() {
        // Now, we have to return a value from this method.

        // Start by declaring a local variable and filling it with some data.
        String stringValue = "Rectangle with location {";

        // We can "add" strings together to form a bigger string with the contents mashed next to each other (aka "concatenated").
        stringValue = stringValue + this.x + ",";

        // By "adding" this.y (the current object's y property) to a string, it also gets converted from an integer to a string without us needing to say anything special.
        stringValue = stringValue + this.y + "}";

        // We can take some shortcuts, too, by using the += operator so we don't have to rewrite stringValue twice every time!
        stringValue += ", width: " + this.width;

        // Remember, we don't need to use "this" when the name is not ambiguous, but it typically makes it clearer that some data is coming from the object instead of a local variable.
        stringValue += ", height: " + height;

        // Once we have a result value and no other code needs to be executed, we have to *return* it as the result of the method. Constructors and methods with "void" as their return type do not do this (though void methods can just say "return;")
        return stringValue;
    }
}

Now, when we run our program, it will print out the following:

现在,当我们运行我们的程序时,它会打印出以下内容:

Rectangle with location: {5,10}, width: 20, height: 30

We can clean up the toStringmethod a lot here, so our class looks like this:

我们可以toString在这里清理很多方法,所以我们的类看起来像这样:

public class Rectangle {
    public int x;
    public int y;
    public int width, height;

    public Rectangle(int x, int y, int w, int h) {
        this.x = x;
        this.y = y;
        width = w;
        height = h;
    }

    public static void main(String[] args) {
        Rectangle box = new Rectangle(5, 10, 20, 30);
        System.out.println(box);
    }

    @Override
    public String toString() {
        return "Rectangle with location {" + x + "," + y + "}, width: " + width + ", height: " + height;
    }
}

Going Further

走得更远

Now, what we need to do is to get our Rectangle to show up on the screen. In order to do this, we're going to need to bring in the AWT framework (Advanced Window Toolkit) and the Swing framework. This isn't the only way to get it to show up on screen, but it works for our purposes.

现在,我们需要做的是让我们的 Rectangle 显示在屏幕上。为了做到这一点,我们需要引入 AWT 框架(Advanced Window Toolkit)和 Swing 框架。这不是让它显示在屏幕上的唯一方法,但它适用于我们的目的。

Thanks to @KanadJadhav for posting this example in his answer here.

由于@KanadJadhav对他的回答张贴这个例子在这里

We need to add some imports to the top of the file, and start modifying our mainmethod so that it sets up AWT and Swing and uses them to draw our rectangle. Add this to the top of the file:

我们需要在文件顶部添加一些导入,并开始修改我们的main方法,以便它设置 AWT 和 Swing 并使用它们来绘制我们的矩形。将此添加到文件的顶部:

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

These bring in the classes you'll need to create a program window and draw your rectangle on it. I won't get into how AWT and Swing work in detail, but I'll show you what you need.

这些引入了创建程序窗口并在其上绘制矩形所需的类。我不会详细介绍 AWT 和 Swing 的工作原理,但我会告诉您您需要什么。

In order to get your Rectangle to appear on-screen, we need to create a window, set its size, and fill the window's content pane with a component which will draw the rectangle onto the screen. Afterwards, we just make our window visible, and Swing handles all the dirty work, keeping our program alive until the window is closed.

为了让你的矩形出现在屏幕上,我们需要创建一个窗口,设置它的大小,并用一个组件填充窗口的内容窗格,该组件会将矩形绘制到屏幕上。之后,我们只是让我们的窗口可见,Swing 处理所有脏活,让我们的程序保持活动状态直到窗口关闭。

public static void main(String[] args) {
    Rectangle box = new Rectangle(5, 10, 20, 30);

    // New stuff - Create a program window and set it up.
    JFrame window = new JFrame();

    // Tell Swing to exit the program when the program window is closed.
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Set the window boundaries to be 300x300 on the screen, and position it 30 pixels from the top and left edges of the monitor.
    window.setBounds(30, 30, 300, 300);

    // Get the content pane of the window, and give it our own custom component.
    window.getContentPane().add(new JComponent() {  // Not a typo - this is some advanced magic called an "anonymous class".
        Rectangle myBox = box;    // Give the component a reference to our box object.
        public void paint(Graphics g) {
            g.drawRect(myBox.x, myBox.y, myBox.width, myBox.height);
        }
    });

    // Make our window appear.
    window.setVisible(true);
}

This is a little sloppy and hard to follow, so you'll have to excuse my hand-waving. I feel I've explained some of the tricky bits in the comments (like the anonymous class - that's a pretty advanced Java feature), but in general, this is the type of code that the Swing documentation shows, and much of it doesn't need to be understood completely to be used. If you want, you can do your own research on the Swing framework, the AWT Graphics class, or Java Anonymous classesthrough the examples at the links I've provided.

这有点草率且难以理解,所以你必须原谅我的挥手。我觉得我已经在评论中解释了一些棘手的部分(例如匿名类 - 这是一个非常高级的 Java 功能),但总的来说,这是 Swing 文档显示的代码类型,其中大部分都没有需要完全理解才能使用。如果需要,您可以通过我提供的链接中的示例对Swing 框架、AWT图形类或 Java匿名类进行自己的研究。