java - 如何为对象分配特定的 int 值?

标签 java arrays swing jpanel

我目前正在尝试制作一款深受“冒险资本主义”启发的游戏,作为 Java 的学校项目。我创建了一个保存值(临时的,会更改)的数组,当我按下按钮(upgradeButton)时,我想要一个数组/for来搜索数组的正确位置到对象的正确位置。

例如,5 个对象中的第 3 个从 15 美元(起始值)升级到 20 美元。我已经尝试过,但似乎没有任何效果,我对 Java 相当陌生,于 2016 年 9 月开始使用 java。这是我的代码,请询问有关它的任何内容,它有点困惑,但一旦我让一切正常工作我就会清理它:) ATM 我只使用 1 个对象只是为了让它工作,但稍后我会用列表等重写。

“投资类别”

public class Investments {
public int x, y, bX, bY, bWidth, bHeight, width, height, yLoad, money;
int worth[] = { 10, 20, 30, 40, 50, 60, 70, 80};
float Loading;

//String path;

//boolean ifAdd = false;

GamePanel gp;
Image invest;
ImageIcon investImage = new ImageIcon("images/image.png");

public Investments(int x, int y, int worth, float Loading) {
    this.x = x;
    this.y = y;
    this.Loading = Loading;
    width = 64;
    height = 64;
    yLoad = 0;
    bX = x + 75;
    bY = y + 30;
    bWidth = 60;
    bHeight = 20;
}

JPanel类

    public GamePanel() {
    if (isRunning)
        return;

    //invest = createInvestList(8);
    invest = new Investments(30, 30, 20, 1f);
    moneyButton = new JButton("$$$"); moneyButton.setBounds(175, 61, 55, 20); add(moneyButton); moneyButton.addActionListener(this);
    upgradeButton = new JButton("^"); upgradeButton.setBounds(175, 37, 55, 20); add(upgradeButton); upgradeButton.addActionListener(this);

    this.setBackground(Color.GRAY);
    addMouseListener(this);

    thread = new Thread(this);
    thread.start();
}

JPanel再往下,按钮法

        if(ae.getSource() == upgradeButton){
        //what to do here? perhaps a for loop that scans the array and then attach it to the specific object? 
    }
}

代码很乱,是的。如前所述,将进行清理,如果难以阅读/理解,请抱歉。正如我也提到的,今年 9 月开始使用 java,有点新,我需要一些帮助,如何获得正确的对象的正确“值(value)”。(worth[i] = object[3] 等)

最佳答案

How do I asign a object with specific int value?

如果您询问如何从创建的对象集合中访问特定对象,您可以创建一个数组列表或对象数组,并通过数组列表索引访问特定对象:

ArrayList<Investment> myInvestments = new ArrayList<Investment>();

myInvestments.add(/*write your investment object here*/);

myInvestments.get(2);             //get 3rd investment object 

myInvestments.get(2).upgrade();   //upgrade the 3rd investment object in the list
<小时/>

对于使用数组:

Investment[] myInvestments = new Investment[20];

myInvestments[0] = new Investment();  //assign investment object to your array

myInvestments[2];                     //get 3rd investment object 

myInvestments[2].upgrade();            //upgrade the 3rd investment object in the array

关于java - 如何为对象分配特定的 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41026933/

相关文章:

php - 获取内部数组键的数组值

java - 在 Java Swing 中获取和设置 JScrollBar 位置

java - 控制自定义 Synth 外观和感觉中复选框的布局

java - 如何根据登录的用户设置可见的 JButton?

java - 在准备好的语句中获取列名而不是值

java - 计算 jTable netbeans 中某一列中值的总和

c - For 循环未按预期工作

c - 如何找到数组的大小(从指向数组第一个元素的指针)?

java - 如何找到链表的最大/最小元素

java - CountDownTimer Java 等价物