【问题标题】:Java: How can I add a name to a rectangle which is a node of a graph?Java:如何向作为图形节点的矩形添加名称?
【发布时间】:2020-06-03 19:47:19
【问题描述】:

我是 Java 新手,但在执行以下练习时遇到了一些问题:
这是我必须做的:

据我所知,使用 java.awt.Rectangle 制作的 Rectangle 具有 x 和 y 坐标以及宽度和高度。所以,我可以创建一个这样的矩形(例如):

Rectangle node = new Rectangle (5,10,15,20);

但是,我不确定如何为该矩形添加名称。到目前为止,我已经创建了一个这样的 Node 类:

import java.awt.Rectangle;

public class Node {
    private int x;
    private int y;
    private int width;
    private int height;
    private String name;

    public Node(int x, int y, int width, int height, String name) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.name = name;
    }

}

我不确定这是否正确,因为据我了解,矩形对象在我的节点构造函数中已经有 5 个参数中的 4 个。那么正确的做法是什么?我应该为一个矩形创建一个父类,然后创建一个节点子类,我只需在构造函数中添加一个名称吗?希望这已经足够清楚了,我真的很困惑...感谢您的宝贵时间!

【问题讨论】:

    标签: java awt


    【解决方案1】:

    您的构造函数已经看起来不错了。据我了解:

    一个节点有一个 Rectangle 和一个 Name。

    所以你的班级成员应该是:

    public class Node{
        private String name;
        private Rectangle rectangle;
    
        ... 
    }
    

    通过保持相同的构造函数签名,您可以初始化这两个成员 namerectangle

    对于第三点,您需要有第二个不带参数的构造函数,默认情况下初始化名称和矩形。 默认构造函数如下所示:

    public Node(){
          ...
    }
    

    编辑(回答您的评论)

    几乎 :) 如果您必须在构造函数中传递一个矩形,或者更像是位置和大小,我不太清楚。如果它取决于我,我实现了它们。

    public class Node{
    
        private String name;
        private Rectangle rectangle;
    
        public Node(){
            this.name = "some default name";
            this.rectangle = // however you initialise your default rectangle
        }
    
       public Node(String name, int x, int y, int width, int height){
           this.name = name;
           this.rectangle = .... // use x,y, width and height to create a new rectangle
       }
    
       // your solution:
       public Node(String name, Rectangle rectangle){
           this.name = name;
           this.rectangle = rectangle;
       }
    

    【讨论】:

    • 谢谢!我不确定我是否正确理解了这一点,我的代码应该是这样吗?导入 java.awt.Rectangle;公共类节点 { 私有字符串名称;私有矩形矩形;公共节点(矩形矩形,字符串名称){ this.rectangle=rectangle; this.name = 名称; } 公共节点() { this.rectangle=rectangle; this.name = 名称; } }(我不确定如何在评论中显示代码,我对堆栈溢出有点陌生,抱歉)
    猜你喜欢
    • 2022-07-04
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多