根据按钮按下情况选择阵列存储的内容

发布于 2024-12-13 11:18:26 字数 227 浏览 0 评论 0原文

我正在尝试找到一种方法来根据用户在 GUI 上按下的按钮来选择数组存储的内容。

显然,由于变量名相同,这不会编译。

计算在循环外部执行,但使用“值”。我只是希望用户能够根据他们按下的按钮确定数组中设置的值。明显的问题是无法两次使用名称“values”,这就是我遇到的问题,因为我有一个需要变量“values”的 for 循环,并且我不想重新添加当很可能有我目前没有看到的简单解决方法时,为每个数据集多次编码。

I'm trying to find a way to pick what an array stores based on which button the user presses on a GUI.

Obviously this will not compile due to the variable name being the same.

The calculations are performed outside of the loop but use "values". I just want the user to be able to determine what values are set in the array based on what button they press. The obvious issue is not being able to use the name "values" twice, which is where I am having a problem as I have a for loop that requires the variable "values" and I don't want to have to be re adding the code several times for each data set when there is most likely an easy workaround that I am currently not seeing.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

深空失忆 2024-12-20 11:18:26

只需将声明拉出来:

double[] Xvalues = null;
if (e.getSource() == X1btn) {
   Xvalues = new double[]{2001,350,799,1004};
}
else if (e.getSource() == X2btn) {
   Xvalues = new double[]{5,62,28,500};
}

Just pull the declaration out:

double[] Xvalues = null;
if (e.getSource() == X1btn) {
   Xvalues = new double[]{2001,350,799,1004};
}
else if (e.getSource() == X2btn) {
   Xvalues = new double[]{5,62,28,500};
}
还给你自由 2024-12-20 11:18:26

更好的方法是子类化 JButton 并将一组值与每个实例相关联。要检索按钮的值,请包含访问器。

例子

public final class JArrayButton extends JButton{
    private final double[] values;

    public JArrayButton(double[] values){
        this.values = values;
    }

    // ... other stuff (e.g. constructors)

    public final double[] getValues(){
        return values;
    }
}

A better approach would be to subclass JButton and associate a set of values with each instance. To retrieve the button's values, include an accessor.

Example

public final class JArrayButton extends JButton{
    private final double[] values;

    public JArrayButton(double[] values){
        this.values = values;
    }

    // ... other stuff (e.g. constructors)

    public final double[] getValues(){
        return values;
    }
}
情何以堪。 2024-12-20 11:18:26

如果您在循环之外创建数组会怎样?
双 Xvalues[] = 新 Xvalues[5]; //或者任何你想要的大小

,然后使用 if/else 语句

if (e.getSource() == X1btn) {
Xvalues ={2001,350,799,1004};
} else if (e.getSource() == X2btn) {
Xvalues={5,62,28,500};
}

What if you create the array ourside the loop.
double Xvalues[] = new Xvalues[5]; //or whatever size you want

and then use if/else statement

if (e.getSource() == X1btn) {
Xvalues ={2001,350,799,1004};
} else if (e.getSource() == X2btn) {
Xvalues={5,62,28,500};
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文