0

我在自制的 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);
}

}

那么,我哪里错了?真假是判断墙是黑还是黄,没什么好担心的。

4

1 回答 1

1

您已将主布局设置为BorderLayout使用this.setLayout(new BorderLayout());

然后,您将其添加GridPane到中心位置this.add(gridPane,BorderLayout.CENTER);

然后,您尝试使用...将墙壁添加到主布局中this.add(wall, JLayeredPane.DEFAULT_LAYER);,但主布局是BorderLayout

这会给你带来一些问题

更新

您遇到的另一个问题是Wall#paintComponent方法。

您正在绘制偏离x1y1位置的线,但组件已经定位在该点。

任何组件的左上角始终为 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())...

于 2012-11-03T10:40:33.890 回答