我试图操作的代码是绘制方法...我试图通过均匀填充方块来显示棋盘,但是当我运行程序并将滑块移动到均匀时它给了我一个列,黑色的一个列,空的等等。 在奇数时它是国际象棋棋盘
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Blobs extends JFrame implements ActionListener, ChangeListener {
private MyCanvas canvas = new MyCanvas();
private JSlider sizeSl = new JSlider(0, 20, 0);
private JButton reset = new JButton("RESET");
private int size = 0; // number of lines to draw
public static void main(String[] args) {
new Blobs();
}
public Blobs() {
setLayout(new BorderLayout());
setSize(254, 352);
setTitle("Blobs (nested for)");
sizeSl.setMajorTickSpacing(5);
sizeSl.setMinorTickSpacing(1);
sizeSl.setPaintTicks(true);
sizeSl.setPaintLabels(true);
add("North", sizeSl);
sizeSl.addChangeListener(this);
add("Center", canvas);
JPanel bottom = new JPanel();
bottom.add(reset);
reset.addActionListener(this);
add("South", bottom);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
size = 0;
sizeSl.setValue(0);
canvas.repaint();
}
public void stateChanged(ChangeEvent e) {
size = sizeSl.getValue();
canvas.repaint();
}
private class MyCanvas extends Canvas {
@Override
public void paint(Graphics g) {
int x, y;
int n = 0;
for (int i = 0; i < size; i++) {
//n = 1 + i;
for (int j = 0; j < size; j++) {
n++;
x = 20 + 10 * i;
y = 20 + 10 * j;
//g.fillOval(x, y, 10, 10);
g.drawRect(x, y, 10, 10);
if (n % 2 == 0) {
g.fillRect(x, y, 10, 10);
}
}
}
}
}
}
答案 0 :(得分:0)
如果按顺序排列NxN国际象棋棋盘的方格,其中N为偶数,则每N个方格你会连续得到两个相等的棋盘。
因此,如果尺寸均匀,则必须相应地调整方法:
for (int i = 0; i < size; i++) {
n += size % 2 + 1;
for (int j = 0; j < size; j++) {
n++;
//...
答案 1 :(得分:0)
问题是你用n计算绘制的矩形的数量。这不适用于奇数。轻松修复:
for (int i = 0; i < size; i++) {
n = (i % 2);
这会将每行的计数器n交替重置为0和1。