【发布时间】:2014-11-30 04:00:06
【问题描述】:
我正在尝试在 java 中创建一个类似于 Minesweeper 但规则/目标略有不同的 JFrame 应用程序。
我创建了一个 12x12 的 JButton 网格,并有一个 JButton 二维数组。
我正在尝试更改单击按钮时的图像(使其成为 X 或金块的图像)。如果每个按钮都有一个单独的名称,我知道该怎么做,但是创建 144 个单独的按钮并为每个按钮命名似乎不合逻辑。
所以我需要做的是在该按钮的单击事件上,更改/设置该按钮的图像,但在我的动作监听器中,如果我知道该按钮的特定数组坐标,我只能弄清楚它。
我的问题是如何更改该特定按钮的图像?或者如何获取按钮[?][?] 的值,以便更改该按钮的图像?
谢谢!
public class GoldPanel extends JPanel{
ImageIcon xImage = new ImageIcon("x.png");
ImageIcon goldImage = new ImageIcon("");
losingButtonListener loseButton = new losingButtonListener();
winningButtonListener winButton = new winningButtonListener();
JButton[][] button = new JButton[12][12];
//creates the layout
GridLayout layout = new GridLayout(12,12);
Random myRand = new Random();
public GoldPanel(){
//creates panel for name/title/score/etc
JPanel titlePanel = new JPanel();
add(titlePanel);
JLabel title = new JLabel("Welcome to the Goldmine Game!");
titlePanel.add(title);
//creates panel for the game board
JPanel gamePanel = new JPanel();
add(gamePanel);
gamePanel.setLayout(layout);
for(int i=0;i<12;i++)
{
for(int j=0;j<12;j++)
{
button[i][j] = new JButton(" ");
gamePanel.add(button[i][j]);
button[i][j].addActionListener(loseButton);
}
}
button[0][0].addActionListener(winButton);
}//end constuctor
private class losingButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}//actionPerformed
}//buttonListener
private class winningButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("you win");
}//actionPerformed
}//winningButtonListener
}//end GoldPanel class
【问题讨论】:
标签: java arrays eclipse jbutton imageicon