This is part of a connect 4 game. I'm trying to get a picture to move each time a player makes a move by calling paintComponent but java won't let me. How do I move a picture in my code?

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

    public class PanelC4 extends JPanel
   {
      private Board board=new Board();
      private Piece[][] boardArray=new Piece[6][7];
      private ImageIcon red, white, blue;
      private int turn;
      //private Scoreboard scoreboard;
       public PanelC4()
      {
         ImageIcon red=new ImageIcon("red.jpg");
         ImageIcon white=new ImageIcon("white.jpg");
         ImageIcon blue=new ImageIcon("blue.jpg");
         setLayout(new BorderLayout());
         board.setLayout(new GridLayout(6,7));
         for(int j=0; j<6; j++)
         {
            for(int k=0; k<7; k++)
            {
               boardArray[j][k]=new Piece(0,white,20+(k*60),(j*60)+7);
               boardArray[j][k].addActionListener(new Listener1());
               board.add(boardArray[j][k]);
            }
         }
         add(board, BorderLayout.CENTER);
         
      //scoreboard=new Scoreboard();
      //add(scoreboard, BorderLayout.NORTH);
      }
	//public Piece move(Piece piece, ImageIcon icon, int turn)
	 
	 public void paintComponent(Graphics g)
	 {
	 super.paintComponent(g);
	 JLabel label1=new JLabel();
	 label1.setIcon(icon);
	 int x,y, picY;
	 x=piece.getX();
	 y=piece.getY();
	 g.drawImage(icon.getImage(),x+50,57,null);
	 while(picY!=y+100)
	 {
	 picY=picY+5;
	g.drawImage(icon.getImage(),x+50,picY,null);
	 }
	 if(turn%2==0)
	 Piece j=new Piece(2, blue,x,y);
	 //else
	 Piece j=new Piece(1,red,x,y);
	 return j;


    }
	 public void clear(Piece[][] board)
{
for(int x = 0; x<board.length; x++)
{
for(int y = 0; y<board[0].length; y++)
{
board[x][y] = 0;
}
}
}

	private class Listener1 implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
		if(hasButton)
		JOptionPane.showMessageDialog(null, "There's already a piece there.");
		else
		paintComponent(Graphics g);


		}
	}
}

You shouldn't try to call paintComponent like that, only in the context of overriding paint(...) or somesuch where you already have the Graphics context and Swing knows that you're doing it.
If you want to force a repaint call repaint().

how do I get the picture to move then? and is it possible to get a button to output its coordinates when its pushed? Piece extends JButton and it has coordinates. Is there a way I can get the coordinates of a Piece whenever its pushed so I can tell which one was pushed?

void actionPerformed(ActionEvent e) {
  JButton pressedButton = (JButton)e.getSource();
  int xPos = pressedButton.getX();
  ...
}
This article has been dead for over six months. Start a new discussion instead.