the code im trying to manipulate is the paint method... i'm trying to get it to show a chess board by filling in the squares evenly, but when i run the programme and move the slider to a even number it gives me one column with black one colum with empty etc. when at an odd number it is the chess board

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);
                }
                }
            }
        }
    }
}
有帮助吗?

解决方案

The problem is that you count the number of drawn rectangles with n. This does not work for odd numbers. Easy fix:

for (int i = 0; i < size; i++) {
  n = (i % 2);

This resets your counter n for each row alternately to 0 and 1.

其他提示

If you lay out sequentially the squares of an NxN chess board with N being even, every N squares you'll get two equal ones in a row.

Therefore, if size is even you must adjust your method accordingly:

for (int i = 0; i < size; i++) {
    n += size % 2 + 1;
    for (int j = 0; j < size; j++) {
        n++;
        //...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top