gpt4 book ai didi

java 2D 绘图

转载 作者:行者123 更新时间:2023-11-30 05:09:49 26 4
gpt4 key购买 nike

我正在尝试制作一个绘制函数图形的 swing 应用程序(现在很简单,例如 x+2)但我在根据屏幕坐标制作我的点的数学坐标时遇到问题。我希望它在我的图表中简单地画一条从 P1(0,1) 到 P2(1,2) 的线。

这是我的代码:

import java.awt.*;
import javax.swing.*;
public class Graph extends JPanel {

protected void paintComponent(Graphics g) {
int YP1,YP2;
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;

int h = getHeight();
int w = getWidth();
// Draw axeX.
g2.draw(new Line2D.Double(0, h/2, w, h/2)); //to make axisX in the middle
// Draw axeY.
g2.draw(new Line2D.Double(w/2,h,w/2,0));//to make axisY in the middle of the panel

//line between P1(0,1) and P2(1,2) to draw function x+1
Point2D P1 = new Point2D.Double(w/2,(h/2)+1);
Point2D P2 = new Point2D.Double((w/2)+1,(h/2)+2);
g2.draw(new Line2D.Double(P1,P2));
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Graphe());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}

谢谢。

最佳答案

import java.awt.*;
import javax.swing.*;
public class Graph extends JPanel {
private static final int UNIT = 20;
protected void paintComponent(Graphics g) {
int YP1,YP2;
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;

int h = getHeight();
int w = getWidth();
// Draw axeX.
g2.draw(new Line2D.Double(0, h/2, w, h/2)); //to make axisX in the middle
// Draw axeY.
g2.draw(new Line2D.Double(w/2,h,w/2,0));//to make axisY in the middle of the panel

//line between P1(0,1) and P2(1,2) to draw function x+1
Point2D P1 = new Point2D.Double(w/2,(h/2)+ UNIT);
Point2D P2 = new Point2D.Double((w/2)+ UNIT,(h/2)+ 2*UNIT); //considering 20 = 1 unit in your syste,
g2.draw(new Line2D.Double(P1,P2));
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new Graphe());
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}

尝试此代码阅读注释以获得解决方案

关于java 2D 绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3820225/

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