0

I used Java graphics to create a 500 x 500 Checkers board within a JPanel, which was placed within a JFrame. To make the pieces, I wrote a series of for loops to create JButtons across the board. The following for loops correctly set up the pieces for one side of the board:

    for(int x = 355; x>=55;x-=100)
    {
     Piece p = new Piece();


     p.addActionListener(new ButtonListener());


     p.setBounds(x,5,40,40);

     b.add(p);
    }

    for(int x = 5;x<=355; x+=100)
    {
        Piece p = new Piece();
        p.addActionListener(new ButtonListener());
        p.setBounds(x,55,40,40);
        b.add(p);

    }


     for(int x = 355; x>=55;x-=100)
    {
     Piece p = new Piece();
     p.addActionListener(new ButtonListener());
     p.setBounds(x,105,40,40);
     b.add(p);
    }

However, I just started setting up the pieces for the other side of the board with this for loop, and none of the buttons are being displayed:

     for(int x = 5; x>=355;x+=100)
    {
     Piece p = new Piece();


     p.addActionListener(new ButtonListener());


     p.setBounds(x,255,40,40);

     b.add(p);
    }

Why is this happening?

  • 2
    I don't know about others, but for me to figure out what was wrong, I'd need to see a [minimal example program](http://stackoverflow.com/help/mcve), that would let me experience your problem for myself. I also have to look askance at your use of absolute positioning. If this were my program, my chess board would be a JPanel that held an 8 x 8 grid of colored JPanels, and I'd place my pieces in the center of the holding square (JPanel). Giving each square JPanel a GridBagLayout would allow it to hold the one piece in its center. – Hovercraft Full Of Eels Jun 15 '14 at 20:27
  • What is `b`? Where is it defined? – PM 77-1 Jun 15 '14 at 20:28
  • Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead [use layout managers](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html), or [combinations of them](http://stackoverflow.com/a/5630271/418556), along with layout padding & borders for [white space](http://stackoverflow.com/q/17874717/418556). – Andrew Thompson Jun 16 '14 at 01:27

1 Answers1

5

The loop

for (int x = 5; x >= 355; x += 100) {
    ... 
}

won't ever be entered.

You are setting x to 5. Then, you are checking if x >= 355, which will be false because 5 is not >= 355.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73