gpt4 book ai didi

java - java中的简单十字准线

转载 作者:行者123 更新时间:2023-12-02 13:14:23 25 4
gpt4 key购买 nike

我必须画一个简单的十字准线。我所看到的只是一个空白面板。

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方法中绘制十字准线,这将取代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);
}

这应该可以做到(实际上确实如此,正如我测试过的那样;))

关于java - java中的简单十字准线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43829330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com