我想要的是我的坐标源和红点之间的动态线。 红点应该留下一丝点,当我重新绘制时,线条不应留下痕迹。
由于我super.paintComponent(gfx)
,现在既没有线也没有点留下痕迹。
任何想法我怎样才能实现动态线和跟踪点?
下面的类是可编译的,因此您可以重建我的问题。
我的主要和JPanel课程是:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String Args[])
{
//Initialize Points
ArrayList<Point> carthCoords = new ArrayList<Point>();
Point p1 = new Point(300,300);
Point p2 = new Point(-300,-200);
carthCoords.add(p1);
carthCoords.add(p2);
//Create JPanel
CoordSystem coordPanel = new CoordSystem(800, 800, carthCoords);
//Display Points on JFrame
JFrame jFrame = new JFrame("Points and Vectors");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(800, 800);
javax.swing.Timer t = new javax.swing.Timer(10, coordPanel);
jFrame.add(coordPanel);
t.start();
jFrame.setVisible(true);
}
}
JPanel课程:
import javax.swing.*;
import java.util.ArrayList;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CoordSystem extends JPanel implements ActionListener{
public int W;
public int H;
ArrayList<Point> points;
public CoordSystem(int width, int height, ArrayList<Point> pointz)
{
this.W = width;
this.H = height;
this.points = pointz;
}
public void paintComponent(Graphics gfx)
{
super.paintComponent(gfx);
setBackground(Color.white);
//Draw Coordinate System
gfx.setColor(Color.blue);
gfx.drawLine(W/2, 0, W/2, H);
gfx.drawLine(0, H/2, W, H/2);
//Draw Points
if (points != null)
{
int x,y;
for (Point p : points)
{
x = (int)p.getX();
y = (int)p.getY();
gfx.setColor(Color.red);
gfx.fillOval((W/2) + x, (H/2) - y, 10, 10);
gfx.setColor(Color.black);
gfx.drawLine(W/2 + x,H/2 - y, W/2, H/2);
}
}
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
for (Point point : points)
{
point.translate(0,-1);
}
repaint();
}
}