好的,这是我正在制作函数绘图器的东西,当您将鼠标移到一条线上时,它会显示坐标。所以我只在面板上设置了一个基本的拉绳来显示鼠标坐标,但我无法正常重新绘制。它似乎画得很好,但在绘画之前没有清除内容这里是我到目前为止的代码。
public class Grapher extends JPanel implements MouseMotionListener{
private final int BORDER_GAP = 15;
private final int MAX_SCORE = 20;
private final int PREF_WIDTH = 800;
private final int PREF_HEIGHT = 650;
private final int GRAPH_POINT_WIDTH = 12;
private static final int GRAPH_INTERVAL = 15;
private static Point mse;
private List<Point> values;
public Grapher(List<Point> values) {
setMse(new Point(0,0));
this.values = values;
addMouseMotionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponents(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
float xScale = ((float) getWidth() - 2 * BORDER_GAP) / (values.size()-1);
float yScale = ((float) getHeight() - 2 * BORDER_GAP) / (MAX_SCORE-1);
g2d.drawString(xScale+"", 50, 50);
g2d.drawString(yScale+"", 50, 70);
g2d.drawString(getWidth()/2+"", 50, 90);
g2d.drawString(mse.x +" " + mse.y, 50, 30);
//create axis
g2d.setColor(new Color(0x7e7e7e));
//x line
g2d.drawLine(BORDER_GAP, (getHeight() - BORDER_GAP)/2, getWidth() - BORDER_GAP, (getHeight() - BORDER_GAP)/2);
//y line
g2d.drawLine(getWidth()/2, getHeight() - BORDER_GAP, getWidth()/2, BORDER_GAP);
}
public Dimension getPreferredSize(){
return new Dimension(PREF_WIDTH, PREF_HEIGHT);
}
private static void createAndShowGui(){
List<Point> values = new ArrayList<Point>();
int maxDataPoints = 20;
for (int i = -GRAPH_INTERVAL; i <= GRAPH_INTERVAL; i++) {
String val = "";
try {
val = EquationSolver.solveEquation(variableReplace('x', i));
} catch (Exception e) {
val ="0";
e.printStackTrace();
}
System.out.println(i + "= " + val);
values.add(new Point(i, Integer.parseInt(val)));
}
Grapher panel = new Grapher(values);
JFrame frame = new JFrame("Grapher");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.pack();
//frame.setLocationByPlatform(true);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndShowGui();
}
});
}
@Override
public void mouseMoved(MouseEvent e) {
setMse(new Point(e.getX(), e.getY()));
removeAll();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
setMse(new Point(e.getX(), e.getY()));
//repaint();
}
好的,这里有一些关于代码在做什么的图像,上面的数字是鼠标位置。重新开始编程:http ://snag.gy/BFrUj.jpg 。在我稍微移动鼠标后:http: //snag.gy/lNqie.jpg
谢谢你的帮助。