gpt4 book ai didi

Java swing - 从 gui 接收内部类的字符串或整数

转载 作者:行者123 更新时间:2023-12-02 04:47:59 26 4
gpt4 key购买 nike

大家好,我并没有真正为我的项目开发 GUI,但我想知道我应该对需要用户输入的部分代码做什么。我对 Java GUI 很陌生,但这就是我们的工作我的课需要使用。

我的代码部分只是从用户那里接收一些整数,很可能是 0 到 10 之间的 slider 。这将确定他们对所遇到的某些问题的痛苦评级,并且我将这些设置在一个数组中,因为那里他们可能会出现 10 个错误,这是我的代码,如下所示:

public void inputPain() {
int[] pain_rating = new int[10];
Arrays.fill(this.pain_rating, 0);
// ^ do I need this if all sliders will be set at zero initially?

// This is where I don't know how to receive an int from the GUI
// presumably there will be 10 sliders that will be for each issue
// which makes me think it is something like

this.pain_rating[index] = pain;

// where index is the slider the user chose and pain is the number
// the user slid it to
}

唯一的问题是我不知道如何从 GUI 中从用户那里接收这些整数。只要知道我从这里去哪里就太棒了。提前感谢

最佳答案

当您创建 slider 时as per this tutorial ,您可以使用事件处理程序从输入中获取值。本教程的相关部分是

framesPerSecond.addChangeListener(this);

它将更改事件处理程序添加到framesPerSecond( slider )。事件处理程序恰好是 this (但它可以是任何东西)。事件处理程序只需实现 ChangeListener 接口(interface),该接口(interface)只有一个方法 public void stateChanged(ChangeEvent e)。然后获取 slider 的值

JSlider source = (JSlider)e.getSource();
(int)source.getValue();

但请参阅教程以获取更多信息。

当然,它不一定是 slider 才能获取数字数据。您可以轻松地使用文本输入并尝试将其解析为整数(即​​使用 Integer.parseInt(String)),如果输入无法解析为,则显示某种错误一个整数。

在大多数情况下,您会发现大多数 GUI 库都使用事件处理程序(也称为“监听器”)来对用户使用react。

关于Java swing - 从 gui 接收内部类的字符串或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505353/

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