import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import gui.ZJM;
public class Bresenham extends JPanel {
private int x0;
private int y0;
private int xEnd;
private int yEnd;
private boolean temp=false;
void setyEnd(int i) {
// TODO 自动生成的方法存根
yEnd=i;
}
void setxEnd(int i) {
// TODO 自动生成的方法存根
xEnd=i;
}
void setY0(int i) {
// TODO 自动生成的方法存根
y0=i;
}
void setX0(int i) {
// TODO 自动生成的方法存根
x0=i;
}
//Graphics g=getGraphics();
@Override
public void paintComponent(Graphics g) {
//super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.translate(getWidth() / 2, getHeight() / 2);
g2d.scale(1, -1);
g2d.drawLine(-400, 0, 400, 0);
g2d.drawLine(0, -400, 0, 400);
temp=true;
//g2d.drawLine(x0, y0, xEnd, yEnd);
//Bresline();
}
public void setPixel(int x,int y){
Graphics g = getGraphics();
Graphics2D g2d = (Graphics2D)g;
g2d.translate(getWidth() / 2, getHeight() / 2);
g2d.scale(1, -1);
g2d.setColor(Color.RED);
g2d.fillOval(x,y,1,1);
}
static void createAndShowGUI(Bresenham a) {
JFrame frame = new JFrame();
// Add your component.
frame.setContentPane(a);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void Bresline(){
int dx=Math.abs(xEnd-x0),dy=Math.abs(yEnd-y0);
int p=2*dy-dx;
int twoDy=2*dy,twoDyMinusDx = 2*(dy-dx);
int x,y;
if(x0>xEnd) {
x=xEnd;
y=yEnd;
xEnd=x0;}
else {
x=x0;
y=y0;
}
setPixel(x,y);
while(x<xEnd) {
x++;
if(p<0)
p+=twoDy;
else {
y++;
p+=twoDyMinusDx;
}
setPixel(x,y);
try {
Thread.currentThread().sleep(250);
}
catch(Exception e){}
}
}
public void bresline(int x0,int y0,int xEnd,int yEnd) {
Bresenham a = new Bresenham();
a.setX0(x0);
a.setY0(y0);
a.setxEnd(xEnd);
a.setyEnd(yEnd);
a.createAndShowGUI(a);
a.Bresline();
}
public static void main(String[] args) throws IOException {
}
}
问题1:为什么Bresline函数调用在画出坐标轴之前?
问题 2:如何修改才能在坐标轴上作图
补充:本意是想从另一个类中调用bresline(int,int,int,int)函数来实现作图,但测试的时候发现将x0,y0,yend,xend设为常数后从主函数调用bresline()函数就对了