【问题标题】:how to import one class to another如何将一个类导入另一个类
【发布时间】:2021-12-01 07:21:21
【问题描述】:

我有两门课,其中一门是主班。我需要将另一个类导入缅因州。我知道你需要创建这个类的一个对象,但是如何实现呢?

// basic main

import javax.swing.*;

import java.awt.*;

public class Main {

    public static void main(String[] args) {

        int w = 640;

        int h = 480;

        JFrame f = new JFrame();
        Object g = null;
        Drawing dc = new Drawing(Graphics g);
        f.setSize(w, h);
        f.setTitle("Digits");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

// another class which i need import 

import java.awt.*;

import java.awt.geom.*;

import javax.swing.*;


class Drawing extends JComponent {

    public Drawing() {

    }
    @Override
    protected void paintComponent(Graphics g){
        Graphics2D g2d = (Graphics2D) g;

        RenderingHints rh = new RenderingHints(
                RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHints(rh);

        Path2D.Double curve = new Path2D.Double();
        curve.moveTo(250,400);
        curve.curveTo(350,300,500,300,600,400);
        g2d.draw(curve);
    }
}

【问题讨论】:

  • 如果它在同一个包中,你很高兴。否则import package.path.morepaths.Drawing;

标签: java class object import


【解决方案1】:

如果它在同一个包中,则不需要导入类 - 只需创建类的对象,如下所示:

Drawing draw = new Drawing();// this should work for you.

如果不在同一个包中,只需导入 包名Drawing

package packageName// assuming you have this line already in your code

import packageNameWhichContainsTheClassYouWantToImport.Drawing  
import javax.swing.*;

import java.awt.*;

public class Main {

    public static void main(String[] args) {

        int w = 640;

        int h = 480;

        JFrame f = new JFrame();
        Object g = null;
        Drawing dc = new Drawing(Graphics g);
        f.setSize(w, h);
        f.setTitle("Digits");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

您也可以通过使用类的完全限定名称来创建对象而不导入类,例如

myPackage.Drawing draw = new Drawing();

【讨论】:

  • 它和 main 在同一个包中。你写你的包是什么意思?
  • 你没有提到包名,如果在同一个包中你可以直接创建类的实例。我已经更新了我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-15
  • 2014-11-14
  • 1970-01-01
  • 2019-08-23
  • 2021-07-05
  • 1970-01-01
  • 2016-04-05
相关资源
最近更新 更多