Domanda

I already checked this duplicate question and other similar ones and it didn't help. I am trying to add an png to a button when it is clicked. The program is a variable sized tic-tac-toe game for school.

Right now I have:

private ImageIcon X_MARK = new ImageIcon("x.png");
private ImageIcon O_MARK = new ImageIcon("o.gif");
private JButton[][] cells;

...

    cells = new JButton[size][size];
    JPanel board = new JPanel(new GridLayout(size, size));
    board.setBorder(new LineBorder(Color.BLACK, 1));

    ButtonListener listener = new ButtonListener();

    for (int i = 0; i < size; i++)
        for (int j = 0; j < size; j++) {
            cells[i][j] = new JButton();
            cells[i][j].addActionListener(listener);
            board.add(cells[i][j]);
        }
    JFrame ttt = new JFrame();
    ttt.add(board);
    ttt.setTitle("Show GUI Components");
    ttt.setSize(60*size, 60*size);
    ttt.setLocation(0, 0);
    ttt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ttt.setVisible(true);

...

class ButtonListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {

        int i, j;

        for (i = 0; i < size; i++)
            for (j = 0; j < size; j++)
                if (e.getSource() == cells[i][j]) {
                    if ((i + j) % 2 == 0) {
                        cells[i][j].setBackground(Color.GREEN);
                        cells[i][j].setIcon(X_MARK);
                    } else {
                        cells[i][j].setBackground(Color.CYAN);
                        cells[i][j].setIcon(O_MARK);
                    }
                }

    }
}

That is all the relevant code I think. I am using Eclipse and I have x.png and o.png in the src folder and the bin folder of the the project. I have also tried a couple of variants I have seen on SO and google searches like, new ImageIcon("C:/Users/BigBoy/workspace_1/EventDriven/src/x.png");, new ImageIcon("src/x.png");, and some other ones involving getClass().getResource among other things. I don't know what else to try. I know I've done this in the past and didn't have this much trouble.

I added .setBackground(Color.GREEN); just to make sure my clicks were registering properly and they are, the problem to me seems to be with the declaring/initializing of the ImageIcon.

NOTE: Right now my button listener just makes the checker board pattern, I will get to actually putting each player's mark after I figure out this icon problem.

È stato utile?

Soluzione

You need to understand resources which is what you will want to use. They are located relative to the class files. If the images are with the class files, then

  • get your image as a resource
  • Create an ImageIcon from the Image.

i.e., something like:

package whateverpackeyouareusing;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;


public class DefaultFoo {
   public static void main(String[] args) throws IOException {
      String resource = "x.png";
      URL url = Class.class.getResource(resource);
      BufferedImage img = ImageIO.read(url);
      Icon icon = new ImageIcon(img);
      JOptionPane.showMessageDialog(null, icon);
   }
}

Edit: A better example per Andrew Thompson:

package some.package;

import java.awt.Image;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;


public class PlayWithImages {
   public static final String X_RESOURCE = "x.png";
   private Icon xIcon;

   public PlayWithImages() throws IOException {
      URL xImgUrl = getClass().getResource(X_RESOURCE);
      Image xImg = ImageIO.read(xImgUrl);
      xIcon = new ImageIcon(xImg);
   }

   public Icon getXIcon() {
      return xIcon;
   }

   public static void main(String[] args) {
      try {
         PlayWithImages playWithImages = new PlayWithImages();
         Icon xIcon = playWithImages.getXIcon();
         JOptionPane.showMessageDialog(null, xIcon);
      } catch (IOException e) {
         e.printStackTrace();
      }

   }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top