此代码用于移动屏幕截图中显示的图像。
我想要做的是当我点击按钮时,它应该像
一样移动 国际象棋中的骑士。它根本不会移动,显示以下错误。这是什么问题?我上传了我的代码。
感谢您的帮助并考虑
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BoardClass extends JFrame{
private Container contents;
private JButton[][] squares = new JButton[8][8];
private Color colorBlack = Color.BLACK;
private Color colorOrange = Color.ORANGE;
private int sheeprow=7;
private int sheepcol=0;
private int woolfrow1=0;
private int woolfcol1=1;
private int woolfrow2=0;
private int woolfcol2=3;
private int woolfrow3=0;
private int woolfcol3=5;
private int woolfrow4=0;
private int woolfcol4=7;
private ImageIcon sheep = new ImageIcon("sheep.PNG");
private ImageIcon wolf = new ImageIcon("wolf.PNG");
public BoardClass()
{
super("Sheep and wolf game");
contents = getContentPane();
contents.setLayout(new GridLayout(8, 8));
ButtonHandler buttonhandler = new ButtonHandler();
for(int i=0;i<8;i++)
{
for(int j=0;j<8;j++)
{
squares[i][j] = new JButton();
if((i+j)%2!=0) // it allows to show black blocks
{
squares[i][j].setBackground(colorBlack);
}
else
{
squares[i][j].setBackgroun(colorOrange);
}
contents.add(squares[i][j]);
squares[i][j].addActionListener(buttonhandler);
}
}
squares[sheeprow][sheepcol].setIcon(sheep);
/*squares[woolfrow1][woolfcol1].setIcon(wolf);
squares[woolfrow2][woolfcol2].setIcon(wolf);
squares[woolfrow3][woolfcol3].setIcon(wolf);
squares[woolfrow4][woolfcol4].setIcon(wolf);*/
setSize(500,500);
setResizable(false);
setLocationRelativeTo(null); //centers window
setVisible(true);
}
private boolean isValidMove(int i, int j)
{
int rowDelta = Math.abs(i-sheeprow);
int colDelta = Math.abs(j-sheepcol);
if((rowDelta==1) && (colDelta==2))
{
return true;
}
if((colDelta==1)&&(rowDelta==2))
{
return true;
}
return false;
}
private void processClick(int i, int j)
{
if(isValidMove(i,j)==false)
{
return;
}
squares[sheeprow][sheepcol].setIcon(null);
squares[i][j].setIcon(sheep);
sheeprow = i;
sheepcol = j;
}
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
for(int i=0;i<8;i++)
{
for(int j=0;i<8;j++)
{
if(source==squares[i][j])-- this part showing some error
{
processClick(i,j);
return;
}
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new BoardClass();
}
}