I have two classes, one of them is main main. I need to import another class into the maine. I understand that you need to create an object of this class, but how to implement it?
// 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);
}
}
If it's in the same package, you don't need to import the class - simply create an object of the class like below:
Drawing draw = new Drawing();// this should work for you.
If it's not in the same package, just import the package name with class 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);
}
}
You can also create an object without importing the class by using fully qualified name of the class, like
myPackage.Drawing draw = new Drawing();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.