我正在尝试制作战舰java游戏,开始时我创建了两个jbutton网格并用于数组来检查jbuttons。 点击一个jbutton,因为我保持所有jbuttons为空,jbutton的颜色应该改变。 还有很多东西需要添加才能使它成为一个完整的游戏,但是点击时jbutton颜色的基本变化是不起作用的。 这是调用我的mpanel文件的第一个文件,其中所有工作都已完成。
mPanel mPanel = new mPanel();
frame.getContentPane().add(mPanel); //to add panel
frame.pack(); //
//这是第二个文件
GridListener gridListener = new GridListener();
int count=0;
//count is kept to keep a check if itsplayer1 or 2's turn
public mPanel()
{
title = new JLabel("BATTLESHIP!");
titlePanel = new JPanel();
titlePanel.add(title);
gridButton = new JButton[10][10];
gridButton1 = new JButton[10][10];
gridPanel = new JPanel();
gridPanel1= new JPanel();
gridPanel.setLayout(new GridLayout(10, 10));
gridPanel1.setLayout(new GridLayout(10, 10));
for (int r = 0; r < gridButton.length; r++)
for (int c = 0; c < gridButton[r].length; c++)
{
gridButton[r][c] = new JButton();
gridButton[r][c].setBackground(COLOR_UNCLICKED);
gridButton[r][c].setEnabled(true);
gridButton[r][c].addActionListener(gridListener);
gridPanel.add(gridButton[r][c]);
}
gridPanel1.setLayout(new GridLayout(10, 10));
for (int r = 0; r < gridButton1.length; r++)
for (int c = 0; c < gridButton1[r].length; c++)
{
gridButton1[r][c] = new JButton();
gridButton1[r][c].setBackground(COLOR_UNCLICKED);
gridButton1[r][c].setEnabled(true);
gridButton1[r][c].addActionListener(gridListener);
gridPanel1.add(gridButton1[r][c]);
}
this.setLayout(new BorderLayout());
this.add(titlePanel, "North");
this.add(gridPanel, BorderLayout.LINE_START);
this.add(gridPanel1, BorderLayout.LINE_END);
this.setPreferredSize(new Dimension(1100, 400));
board = new int[10][10];//imagine board is kept below grid buttons and whatever happens on grid buttons i store that change in this array.
for (int r = 0; r < board.length; r++)
for (int c = 0; c < board.length; c++)
{
board[r][c] = UNCLICKED;
gridButton[r][c].setEnabled(true);
}
board1 = new int[10][10];
for (int r = 0; r < board1.length; r++)
for (int c = 0; c < board1.length; c++)
{
board1[r][c] = UNCLICKED;
gridButton1[r][c].setEnabled(true);
}
}
class GridListener implements ActionListener
{
public void actionPerformed1(ActionEvent evt)
{
if(count%2==0)
{
for (int r = 0; r < gridButton.length; r++)
for(int c = 0; c < gridButton[r].length; c++)
{
if (evt.getSource() != gridButton[r][c])
continue;
handleGridButton(r,c);
return;
}
}
else
{
System.out.println(count);
for (int r = 0; r < gridButton1.length; r++)
for(int c = 0; c < gridButton1[r].length; c++)
{
if (evt.getSource() != gridButton1[r][c])
continue;
handleGridButton(r,c);
return;
}
}
}
答案 0 :(得分:0)
解决
actionPerformed1可以/永远不会被调用 - 而是将功能移动到actionPerformed方法。 只是不能将行动称为“即使它”。