我在自制的 gridPanel 上的 JFrame 中画线。
问题是,我在两点之间画线。当我在点 1 和点 2 之间有一条线以及在点 2 和点 3 之间有一条线时,这些线应该连接起来。然而事实并非如此,两者之间有一个小的差距,不知道为什么。但它直到指定点结束时才绘制。(起点是正确的。)
这是JFrame的代码:
public void initialize(){
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 400));
gridPane = new GridPane();
gridPane.setBackground(Color.WHITE);
gridPane.setSize(this.getPreferredSize());
gridPane.setLocation(0, 0);
this.add(gridPane,BorderLayout.CENTER);
//createSampleLabyrinth();
drawWall(0,5,40,5); //These are the 2 lines that don't connect.
drawWall(40,5,80,5);
this.pack();
}
drawWall 调用的方法调用 GridPane 中的方法。gridPane 中的相关代码:
/**
* Draws a wall on this pane. With the starting point being x1, y1 and its end x2,y2.
* @param x1
* @param y1
* @param x2
* @param y2
*/
public void drawWall(int x1, int y1, int x2, int y2) {
Wall wall = new Wall(x1,y1,x2,y2, true);
wall.drawGraphic();
wall.setLocation(x1, y1);
wall.setSize(10000,10000);
this.add(wall, JLayeredPane.DEFAULT_LAYER);
this.repaint();
}
此方法创建一堵墙并将其放入 Jframe。墙的相关代码:
public class Wall extends JPanel {
private int x1;
private int x2;
private int y1;
private int y2;
private boolean black;
/**
* x1,y1 is the start point of the wall (line) end is x2,y2
*
* @param x1
* @param y1
* @param x2
* @param y2
*/
public Wall(int x1, int y1, int x2, int y2, boolean black) {
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
this.black = black;
setOpaque(false);
}
private static final long serialVersionUID = 1L;
public void drawGraphic() {
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if(black){
g2.setColor(Color.BLACK);
g2.setStroke(new BasicStroke(8));
} else {
g2.setColor(Color.YELLOW);
g2.setStroke(new BasicStroke(3));
}
g2.drawLine(x1, y1, x2, y2);
}
}
那么,我哪里错了?真假是判断墙是黑还是黄,没什么好担心的。