I have two point coordinates. One start point and one end point.
I want to draw an ellipse between these two points in a Java Swing application.
How can i do this using Graphics 2d or 3d.
final Point p1 = new Point(17, 58);
final Point p2 = new Point(324, 312);
final Ellipse2D.Double el = new Ellipse2D.Double(p1.x > p2.x ? p2.x : p1.x,
p1.y > p2.y ? p2.y : p1.y,
60,
Math.abs(p1.y - p2.y));
height is 60 here t can be vary.
Here the x and the y coordinates are the starting point coordinates
How can I use one variable as fixed end point coordinate, to draw my ellipse?
please see the image below
For custom paintings you need to use paintComponent()
method of JComponent
, for example JPanel
. Read more about that.
Seems you are looking for something like next:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.Ellipse2D;
import java.beans.Transient;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test extends JFrame{
public Test(){
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
private void init() {
final Point p1 = new Point(210, 280);
final Point p2 = new Point(160, 190);
final Ellipse2D.Double el = new Ellipse2D.Double(p1.x > p2.x ? p2.x : p1.x,
p1.y > p2.y ? p2.y : p1.y,
Math.abs(p1.x - p2.x),
Math.abs(p1.y - p2.y));
JPanel p = new JPanel(){
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.draw(el);
g2d.setColor(Color.RED);
g2d.drawString("P1", p1.x, p1.y);
g2d.drawString("P2", p2.x, p2.y);
};
@Override
@Transient
public Dimension getPreferredSize() {
return new Dimension(p1.x+p2.x+10,p1.y+p2.y+10);
}
};
add(p);
}
public static void main(String[] args) {
new Test();
}
}
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.