gpt4 book ai didi

java - 如何将另一个类的变量调用到 ActionListener 方法中?

转载 作者:太空宇宙 更新时间:2023-11-04 12:28:04 25 4
gpt4 key购买 nike

我想提前道歉,我是java新手,不太了解,所以请跟着我。我想知道如何将我的角色属性从一个类中的一个 ActionListener 方法获取到另一个类中的另一个 ActionListener 方法。我想从用户那里获取有关一个类中的player1的输入,然后在另一个类中使用它们。请帮忙,非常感谢您的时间。

public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub

if(event.getSource() == create){

Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();

JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window

GameWindow gwindow = new GameWindow();
gwindow.setVisible(true);//Open the new window
}

放入

@Override
public void actionPerformed(ActionEvent event) {

Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;

if (event.getSource() == right) {

label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}

if(event.getSource() == fight) {

System.out.println(player1 + " VS. " + Goblin.name);

while(player1.isAlive() && Goblin.isAlive()){

// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");

// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}

// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}

}
}

最佳答案

将 Player1 声明为公共(public)静态成员所以它的值不能改变。

并且您可以通过该特定类的对象使用player1。

    Class First{
//Declare That Character object as a static public here
//Player1;
}
Class Second{
//First Create Object Of that class....
First f = new First(//Parameter For Constructor);
f.Player1;

}

关于java - 如何将另一个类的变量调用到 ActionListener 方法中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38177376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com