我必须绘制一个简单的十字准线。我只看到一个空白面板。
class ChartPanel extends JPanel implements MouseMotionListener{
Graphics2D g;
Dimension dimFrame;
ChartPanel() {
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
drawCrosshair(e.getX(),e.getY());
}
public void mouseDragged(MouseEvent e) {}
protected void paintComponent(Graphics g2) {
g = (Graphics2D)g2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
dimFrame = getSize();
setBackground(Color.WHITE);
}
public Dimension getPreferredSize() {
return new Dimension(700, 500);
}
void drawCrosshair(double x, double y) {
double maxx = dimFrame.getWidth();
double maxy = dimFrame.getHeight();
g.setPaint(Color.BLACK);
g.draw(new Line2D.Double(0, y, maxx, y));
g.draw(new Line2D.Double(x, 0, x, maxy));
}
}
public class pra {
public static void main(String[] args) {
JFrame jFrame = new JFrame();
ChartPanel chartPanel = new ChartPanel();
jFrame.add(chartPanel);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
,它正在进入具有正确值的DrawCrosshair((方法。我不知道我做错了什么。
您可以只处理drawCrosshair()
,然后在paint
方法中绘制Crosshair,该方法将替换paintComponent
方法(实际上我认为您不应该覆盖paintComponent
(:
Graphics2D g;
Dimension dimFrame;
int x, y;
ChartPanel() {
addMouseMotionListener(this);
setPreferredSize(new Dimension(700, 500));
}
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public void mouseDragged(MouseEvent e) {
}
public void paint(Graphics g2) {
super.paint(g2);
g = (Graphics2D) g2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
dimFrame = getSize();
g.clearRect(0, 0, dimFrame.width, dimFrame.height);//clears previous drawings
g.setColor(Color.BLACK);
g.drawLine(x - 10, y, x + 10, y);
g.drawLine(x, y - 10, x, y + 10);
}
这应该做到这一点(实际上它确实是我测试的;((