我在循环中插入了if语句,用于绘制线条以进行换行。 但是,程序的功能就像if语句不存在一样。 if语句不够吗?
import java.awt.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.*;
public class Grid extends Canvas{
Cell[][] maze;
int rows;
int cols;
int pathSize;
double width, height;
public Grid(int rows, int cols, int h, int w) {
this.rows = rows;
this.cols = cols;
maze = new Cell[rows][cols];
setPreferredSize(new Dimension(h,w));
}
public static void main(String[] args){
JFrame y = new JFrame();
y.setLayout(new BorderLayout());
Grid f = new Grid(25,25,400,400);
y.add(f, BorderLayout.CENTER);
y.setSize(450,450);
y.setVisible(true);
y.setDefaultCloseOperation(y.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
int k,j,z=0;
width = getSize().width;
height = getSize().height;
double htOfRow = height / (rows);
for (k = 0; k < rows; k++)
for(j=0; j< rows+1; j++){
if(j!=3){
g.drawLine(z, (int) (k * htOfRow) , (int) (j*(width/rows)) , (int) (k * htOfRow) );
z=(int)(j*(width/rows));
}}
double wdOfRow = width / (cols);
for (k = 0; k < cols; k++)
for(j=0; j< cols+1; j++){
if(j!=3){
g.drawLine((int) (k*wdOfRow) , z,(int) (k*wdOfRow) , (int) (j*(height/cols)));
z=(int)(j*(height/cols));}}
}
}
class Cell{}
答案 0 :(得分:1)
你的绘图循环中有一些逻辑错误。我认为这应该有效:
import java.awt.*;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.*;
public class Grid extends Canvas {
Cell[][] maze;
int rows;
int cols;
int pathSize;
double width, height;
public Grid(int rows, int cols, int h, int w) {
this.rows = rows;
this.cols = cols;
maze = new Cell[rows][cols];
setPreferredSize(new Dimension(h, w));
}
public static void main(String[] args) {
JFrame y = new JFrame();
y.setLayout(new BorderLayout());
Grid f = new Grid(40, 25, 400, 400);
y.add(f, BorderLayout.CENTER);
y.setSize(450, 450);
y.setVisible(true);
}
public void paint(Graphics g) {
int k, j, z = 0;
width = getSize().width;
height = getSize().height;
double htOfRow = height / (rows);
double wdOfRow = width / (cols);
for (j = 0; j < rows; j++) {
for (k = 0; k < cols; k++) {
g.drawLine((int) (k * wdOfRow), (int) (j * htOfRow), (int) (k * wdOfRow), (int) ((j+1) * htOfRow));
}
}
for (j = 0; j < rows; j++) {
for (k = 0; k < cols; k++) {
g.drawLine((int) (k * wdOfRow), (int) (j * htOfRow), (int) ((k+1) * wdOfRow), (int) (j * htOfRow));
}
}
}
class Cell {
}
}