![](/img/trans.png)
[英]How to access objects/arrays defined in JavaScript from Java applets
[英]How to change specific pictures in arrays in java applets?
我正在制作蛇棋和梯子游戏,但有一个小问题。 我无法动弹。
基本上我有一个64块网格,其中有64张图片。 我也有两张图片,它们的大小与我用来移动的瓷砖的大小相同。
当我单击JButton时,图片应该更新了。
这是我的代码以及我尝试过的内容:
public class SnakesandLadders extends Applet implements ActionListener
{
//Part of the grid
int row = 8;
JLabel a[] = new JLabel [(row*row) + 1];
Panel g = new Panel (new GridLayout (row, row));
JLabel grid;
JButton roll;
int playerNum = 1;
int p1space = 0;
int p2space = 0;
public void init ()
{
//The Roll Button
roll = new JButton ("ROLL");
roll.addActionListener (this);
roll.setActionCommand ("roll");
//The Grid Displayed using a for loop
for (int rownum = 7 ; rownum >= 0 ; rownum--)
{
int number = rownum*8;
if (rownum % 2 != 0)
{
for (int i = 7 ; i >= 0 ; i--)
{
a [i+number] = new JLabel (createImageIcon ((i+number) + ".jpg"));
g.add (a [i+number]);
}
}
else
{
for (int i = 0; i < 8; i++)
{
a [i+number] = new JLabel (createImageIcon ((i+number) + ".jpg"));
g.add (a [i+number]);
}
}
}
add (g);
add (roll);
}
public void actionPerformed (ActionEvent e)
{
if (e.getActionCommand ().equals ("roll"))
{//NEED TO FIX THIS PART
{
int n = (int) ((Math.random () * 6) + 1);
playerNum++;
//To choose which picture to update
if (playerNum % 2 != 0) {
turn.setText ("It is Player 1's Turn");
p1space = p1space + n;
a[p1space] = new JLabel (createImageIcon ("p1.jpg"));
}
else {
turn.setText ("It is Player 2's Turn");
p2space = p2space + n;
a[p2space] = new JLabel (createImageIcon("p2.jpg"));
}
}
}
//The picture update method
protected static ImageIcon createImageIcon (String path)
{
java.net.URL imgURL = SnakesandLadders.class.getResource (path);
if (imgURL != null)
{
return new ImageIcon (imgURL);
}
else
{
System.err.println ("Couldn't find file: " + path);
return null;
}
}
}
该代码运行,但没有图片更新。 我确定我在逻辑上犯了一个错误,而且我不知道如何将数组中的图片更改为player1和player2。 谢谢你的帮助。
编辑:当我再次点击滚动按钮时,我也想找出如何删除以前的图标。 谢谢
您没有将创建的新标签添加到g
,因此g
无法调用paint
方法来渲染标签。
可以使用JLabel::setIcon
来更改图像,而不是创建一个新的JLabel
:
// a[p1space] = new JLabel (createImageIcon ("p1.jpg"));
a[p1space].setIcon(createImageIcon ("p1.jpg"));
在执行更改后,您需要调用revalidate()和repaint()方法,这将在您的applet中重新加载您的更改。 在您的方法末尾添加以下两个方法
public void actionPerformed (ActionEvent e)
{
.....
g.revalidate();
g.repaint();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.