我想在Java中用红色创建这个障碍
class Grid extends JFrame{
public Grid(){
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(250,300);
// Set the width,height,number of rows and columns
final GridPanel panel = new GridPanel(300, 300, 10, 10);
add(panel);
}
}
class GridPanel22 extends JPanel{
int width, height, rows, columns;
int gridWidth, gridHeight;
public GridPanel22(int width, int height, int rows, int columns){
gridHeight = height / rows;
gridWidth = width / columns;
setPreferredSize(new Dimension(width, height));
}
public void paint(Graphics g){
g.setColor(Color.red);
for (int i = 1; i <= rows; i++) {
g.drawLine(0, i * gridHeight, width, i * gridHeight);
}
for (int j = 1; j <= columns; j++) {
g.drawLine(j * gridWidth, 0, j * gridWidth, height);
}
}
}
此代码创建了一个网格,但我无法创建障碍。在图片中,那些红色细胞是障碍细胞。为了区分正常网格和主网格,我用红色绘制它。 。我知道在java中有一个名为drawRect()
的函数,但我不确定它是如何工作的。按照图片,从grid(1,1)开始到结束它(5,4)有一个障碍。现在将这些细胞作为障碍细胞,我想将1(一)分配给所有那些细胞意味着(1,1) - > 1,然后(2,1) - > 1 ......(5, 4) - > 1等因此,当我的机器人从一个单元格移动到另一个单元格时,它可以避开这些单元格并找到它自己的去往目的地的路径。
请注意代码中的注释:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
class Grid extends JFrame{
public Grid(){
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final GridPanel panel = new GridPanel(300, 300, 4, 4);
panel.setColor(1, 1, Color.RED); //change cell colors
panel.setColor(2, 3, Color.RED);
add(panel);
pack();
setVisible(true);
}
}
class GridPanel extends JPanel{
//store reference to each cells
Component[][] cells;
public GridPanel (int width, int height, int rows, int columns){
cells = new Component[rows][columns];
//use grid layout to get the layout you want
setLayout(new GridLayout(rows, columns));
setPreferredSize(new Dimension(width, height));
for(int row =0; row < rows; row ++){
for(int col =0; col < columns; col ++){
Component cell = getCell();
cells[row][col] = cell;
add(cell);
}
}
}
//represent each cell as a label
Component getCell() {
JLabel label = new JLabel();
label.setBackground(Color.WHITE);
label.setOpaque(true);
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
return label;
}
//control color of each cell
void setColor(int row, int col, Color color) {
cells[row][col].setBackground(color);
}
public static void main(String[] args) { new Grid(); }
}
如有需要,请随时要求澄清。
您唯一的问题是您没有为传递给构造函数的值分配字段:
public GridPanel22(int width, int height, int rows, int columns) {
this.width = width;
this.height = height;
this.rows = rows;
this.columns = columns;
gridHeight = height / rows;
gridWidth = width / columns;
setPreferredSize(new Dimension(width, height));
}
另外,改变
final GridPanel panel = new GridPanel(300, 300, 10, 10);
至
final GridPanel22 panel = new GridPanel22(300, 300, 10, 10);