我的问题只是TestMethods#newGame()
, or button[2][2].setBackground(Color.red);
, 中的注释行不起作用,说它无法解析为变量。我将在哪里以及如何在顶部编写JButton
,JPanel
等声明行以使注释行起作用?我知道这可能与权限有关,但我让它工作得有多冷?顺便说一句,我知道代码效率极低。感谢您的所有回复,这是我的完整代码:
import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.io.*;
public class Test implements ActionListener
{
public JButton[][] button = new JButton[8][8];
public JFrame frame = new JFrame();
public JPanel[][] square = new JPanel[8][8];
Test() throws IOException
{
frame.setLayout(new GridLayout(9,8));
for(int x=0; x<8; x++)
{
for(int y=0; y<8; y++)
{
square[x][y] = new JPanel();
frame.add(square[x][y]);
square[x][y].setSize(100,100);
square[x][y].setLayout(new GridLayout(1,1));
if(y%2==0)
if(x%2==0)
square[x][y].setBackground(Color.cyan);
else
square[x][y].setBackground(Color.blue);
if(y%2!=0)
if(x%2==0)
square[x][y].setBackground(Color.blue);
else
square[x][y].setBackground(Color.cyan);
button[x][y] = new JButton();
button[x][y] = new TestMethods(x,y);
square[x][y].add(button[x][y]);
button[x][y].setOpaque(false);
button[x][y].setContentAreaFilled(false);
button[x][y].setBorderPainted(false);
button[x][y].addActionListener(this);
}
}
frame.setSize(800,900);
frame.setVisible(true);
}
public static void main(String[] args) throws IOException
{
new Test();
}
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
TestMethods clicked = (TestMethods)obj;
int x = clicked.getGridX();
int y = clicked.getGridY();
System.out.println(x + " : " + y);
}
}
class TestMethods extends JButton
{
private int gridX, gridY;
public TestMethods(int x, int y)
{
this.gridX = x;
this.gridY = y;
}
public int getGridX() {return gridX ;}
public int getGridY() {return gridY ;}
public void newGame()
{
//button[2][2].setBackground(Color.red);
}
}