0

I'm writing a chess program in java that has to be displayed in an applet. I am currently having a problem with filling the array of chess pieces. This is currently being done in the paint() method of my JApplet and I know that's wrong because paint can be called more than once. I have tried creating the array and filling it in my initialize method but that doesn't work at all. Any help would be appreciated.

public class DrawChessBoard extends JApplet
        implements MouseListener, MouseMotionListener {

    ChessPiece myPiece;
    ImageIcon square;
    ImageObserver observer;
    ChessBoard gameBoard;
    boolean isMouseDragging = false;
    int size; //square dimensions   

    public void initialize() {
        setBackground(Color.white);
        Image bSquare = square.getImage();
        size = bSquare.getWidth(observer);
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    public void paint(Graphics h) {
        Graphics2D g = (Graphics2D) h;
        //System.out.println("Am I being called more than once?");
        gameBoard = new ChessBoard(8);
        gameBoard.start();
        gameBoard.paintBoard(g);
        gameBoard.paintComponent(g);
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • 1
    See this [example](http://stackoverflow.com/questions/2561690/placing-component-on-glass-pane/2562685#2562685) and [variation](http://stackoverflow.com/questions/2561690/placing-component-on-glass-pane/2563350#2563350). – trashgod Nov 05 '11 at 03:03
  • 1
    Define "doesn't work at all"? I'd think that's precisely where you'd want to initialize it, at least to get things started. (You might *also* want to initialize it on the start of a new game, for example.) – Dave Newton Nov 05 '11 at 03:04

3 Answers3

3

Don't do program logic in the paint method -- period. That is so wrong in so many ways. Not only will that code be called many times and out of your control, it will slow program graphics to a crawl. Painting should be done in the paintComponent method of a JPanel or other JComponent, and this method should concern itself with painting only.

By the way, where's your init method? That's where most of this code should go.

Here's an example of a chess app done on a JPanel: does-adding-a-jlabel-to-a-jpanel-hide-the-jpanel. Since it's on a JPanel, it can easily be placed in a JApplet's contentPane and displayed in an applet.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
2

You have to separate the game rules from the visualization part of your application.

Read about the Model-View-Presenter or Model-View-Controller design pattern. It will help you.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
pablosaraiva
  • 2,343
  • 1
  • 27
  • 38
0

Try the Model-View-Controller design pattern. In that pattern program logic is performed in the Controller part, but you are doing it in the View part. There be dragons!

trojanfoe
  • 120,358
  • 21
  • 212
  • 242