0

I attempting to place a .jpg icon on top of a JPanel in order to represent a board piece on a board. I have a GUI folder with the .java files and another folder containing the .jpg files.

--Major Edit-- Example Code

When a square is clicked a white icon is meant to be placed then black etc etc. This is a very basic example of what im trying to achieve

import java.awt.Dimension;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class gui extends JFrame implements MouseListener {

/**
 * 
 */
private static final long serialVersionUID = -973341728129968945L;
JLayeredPane layeredPane;
JPanel board;
JLabel piece;
int numSquares;
private boolean currentPlayer;

public gui(){

    Dimension boardSize = new Dimension(600, 600);

    numSquares = 6;
    currentPlayer = true;

    layeredPane = new JLayeredPane();
    getContentPane().add(layeredPane);
    layeredPane.setPreferredSize(boardSize);
    layeredPane.addMouseListener(this);

    board = new JPanel();
    layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);

    board.setLayout( new GridLayout(numSquares, numSquares) );
    board.setPreferredSize( boardSize );
    board.setBounds(0, 0, boardSize.width, boardSize.height);

    for (int i = 0; i < (numSquares * numSquares); i++) {
        JPanel square = new JPanel( new BorderLayout() );
        square.setBorder(BorderFactory.createLineBorder(Color.black));
        square.setBackground(Color.green);
        board.add( square );


     }



}

public static void main(String[] args) {
        JFrame frame = new gui();
        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE );
        frame.pack();
        frame.setResizable(true);
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
     }



@Override
public void mouseClicked(MouseEvent e) {
    JPanel temp =  (JPanel)board.findComponentAt(e.getX(), e.getY());
    System.out.println(e.getX() + " " + e.getY());

    if( currentPlayer ){
        ImageIcon white = new ImageIcon("l/Images/white.jpg");
        piece = new JLabel(white);
        temp.add(piece);
    }
    else{   
        ImageIcon black = new ImageIcon( "/Images/black.jpg");
        piece = new JLabel(black);
        temp.add(piece);
    }
    currentPlayer = !currentPlayer;


}


@Override
public void mouseEntered(MouseEvent e) {


}

@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}

@Override
public void mouseReleased(MouseEvent e) {

}




}
CNevin561
  • 143
  • 1
  • 3
  • 12
  • I deleted my answer because I see that you're already using JPanels as cells for the board. I think you may have to create and show us an [sscce](http://sscce.org) for us to be able to help you. – Hovercraft Full Of Eels Nov 06 '11 at 22:40
  • There isnt anything to show. When the code is run, a 6 by 6 board is created with a black background. Then when a cellis clicked a token ( white or black ) is meant to be placed. But nothing happens. – CNevin561 Nov 06 '11 at 22:46
  • Still if you posted compilable, runnable code, we could more easily study it, understand it, modify it, and possibly help you correct it. Up to you. – Hovercraft Full Of Eels Nov 06 '11 at 22:53
  • ive added a stripped down basic example of my code, thanks again – CNevin561 Nov 06 '11 at 23:11
  • 2
    See also 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 06 '11 at 23:19
  • You where given a working example in your last posting. How is your code different from the working example? Why do you add labels all the time?? The suggestion was to change the Icon on the existing labels! – camickr Nov 07 '11 at 02:20

1 Answers1

4

Don't forget to revalidate and repaint if adding or removing components from a container. I've modified your SSCCE, and have gotten rid of the need to use images to make it runnable by folks who don't have access to your image files (like me!). Changes are noted by the // !! comments:

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;

public class Gui2 extends JFrame implements MouseListener {

   private static final long serialVersionUID = -973341728129968945L;
   JLayeredPane layeredPane;
   JPanel board;
   JLabel piece;
   int numSquares;
   private boolean currentPlayer;

   // !!
   private ImageIcon whiteIcon;
   private ImageIcon blackIcon;

   public Gui2() {
      // !!
      whiteIcon = createIcon(Color.white);
      blackIcon = createIcon(Color.black);

      Dimension boardSize = new Dimension(600, 600);

      numSquares = 6;
      currentPlayer = true;

      layeredPane = new JLayeredPane();
      getContentPane().add(layeredPane);
      layeredPane.setPreferredSize(boardSize);
      layeredPane.addMouseListener(this);

      board = new JPanel();
      layeredPane.add(board, JLayeredPane.DEFAULT_LAYER);

      board.setLayout(new GridLayout(numSquares, numSquares));
      board.setPreferredSize(boardSize);
      board.setBounds(0, 0, boardSize.width, boardSize.height);

      for (int i = 0; i < (numSquares * numSquares); i++) {
         // !! JPanel square = new JPanel(new BorderLayout());
         JPanel square = new JPanel(new GridBagLayout()); // !!

         square.setBorder(BorderFactory.createLineBorder(Color.black));
         square.setBackground(Color.green);
         square.setName(String.format("[%d, %d]", i % numSquares, i
               / numSquares)); // !!
         board.add(square);

      }

   }

   // !!
   private ImageIcon createIcon(Color color) {
      int width = 40;
      int height = width;
      BufferedImage img = new BufferedImage(width, height,
            BufferedImage.TYPE_INT_ARGB);
      Graphics2D g2 = img.createGraphics();
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setColor(color);
      g2.fillOval(0, 0, width, height);
      g2.dispose();
      ImageIcon icon = new ImageIcon(img);
      return icon;
   }

   public static void main(String[] args) {
      JFrame frame = new Gui2();
      frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
      frame.pack();
      frame.setResizable(true);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   @Override
   // !!
   public void mousePressed(MouseEvent e) {
      JPanel temp = (JPanel) board.findComponentAt(e.getX(), e.getY());
      System.out.println(e.getX() + " " + e.getY());
      System.out.println(temp.getName()); // !!

      if (currentPlayer) {
         // !! ImageIcon white = new ImageIcon("l/Images/white.jpg");
         // !! piece = new JLabel(white);
         piece = new JLabel(whiteIcon); // !!
         temp.add(piece);
      } else {
         // !! ImageIcon black = new ImageIcon("/Images/black.jpg");
         // !! piece = new JLabel(black);
         piece = new JLabel(blackIcon); // !!
         temp.add(piece);
      }
      temp.revalidate(); // !!
      temp.repaint(); // !!
      currentPlayer = !currentPlayer;

   }

   @Override
   public void mouseEntered(MouseEvent e) {

   }

   @Override
   public void mouseExited(MouseEvent arg0) {
   }

   @Override
   public void mouseClicked(MouseEvent arg0) {
   }

   @Override
   public void mouseReleased(MouseEvent e) {

   }

}

Also class names should be capitalized, and also you should again make your ImageIcons once. Again, one ImageIcon can be shared by many JLabels. You'll also want to respond to mousePressed not mouseClicked as mouseClicked can be fussy, especially if you move the mouse between press down and mouse release.

Hopefully you've also seen the value of an SSCCE. :)

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • A minor non-programming suggestion - name the squares by a letter A-H (for the column) and a number 1-8 (for the row). e.g. the White King starts on E1. Just like in real chess. – user949300 Nov 07 '11 at 01:22
  • Actually the game I think the OP is creating is Reversi, not Chess, but the naming of the ranks and files is the same as in chess if my memory serves me right. – Hovercraft Full Of Eels Nov 07 '11 at 01:25