我在自制的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);
}
}
那么,我哪里错了?真/假是确定墙应该是黑色还是黄色,没有什么可担心的。
答案 0 :(得分:1)
您已使用BorderLayout
this.setLayout(new BorderLayout());
然后将GridPane
添加到中心位置this.add(gridPane,BorderLayout.CENTER);
然后尝试使用this.add(wall, JLayeredPane.DEFAULT_LAYER);
将墙添加到主布局...但主要布局为BorderLayout
这会给你带来一些问题
<强>已更新强>
您遇到的另一个问题是Wall#paintComponent
方法。
您正在绘制偏离x1
和y1
位置的线条,但此时此组件已经定位。
任何组件的左上角始终为0x0
第g2.drawLine(x1, y1, x2, y2);
行应该更像......
int x = x2 - x1;
int y = y2 - y1;
g2.drawLine(0, 0, x, y);
<强>已更新强>
您还应该避免将组件的大小设置为某个任意值(例如1000x1000),并且更多地依赖于组件为您提供反馈的能力......
public Dimension getPreferredSize() {
int width = Math.max(x1, x2) - Math.min(x1, x2);
int height = Math.max(y1, y2) - Math.min(y1, y2);
if (black) {
width += 8;
height += 8;
} else {
width += 3;
height += 3;
}
return new Dimension(width, height);
}
然后,在添加Wall
时,您可以使用wall.setSize(wall.getPreferredSize())
代替......