【问题标题】:How to get/store value from JSpinner?如何从 JSpinner 获取/存储价值?
【发布时间】:2021-04-19 11:49:56
【问题描述】:

鉴于以下代码,我如何将来自微调器的选定值存储在 thickness1 中?

JSpinner thickn=new JSpinner();
thickn = new JSpinner(new SpinnerNumberModel(1, 1, 60, 1));      
thickn.setFont(new Font("Arial Sans-seriff", Font.BOLD, 12));
thickn.setBounds(120,105,100,25); 
// ...
int thickness1 = (Integer) thickn.getValue();

我可以在 3 点区域添加代码以从微调器中检索值吗?

【问题讨论】:

  • 我通常会保留对数字模型而不是微调器的引用。这使得获取值更简单。 其他提示: 1) new Font("Arial Sans-seriff", ..) 任何平台都没有这种字体。衬线只有一个“f”。但是大多数 Mac OS 系统上没有 Arial,无论如何用户都会期待 Helvetica。使用Font.SANS_SERIF 获得适用于所有平台的最佳无衬线变体。 2) thickn.setBounds(120,105,100,25); Oh boy.. Java GUI 必须在不同的操作系统、屏幕尺寸上工作..
  • .. 屏幕分辨率等。在不同的语言环境中使用不同的 PLAF。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 3) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 4) 看起来值是在同一代码块的末尾进行测试,而不是在更改时进行测试。使用ChangeListener 了解何时获取它。

标签: java swing jspinner


【解决方案1】:

在你的最后一行,尝试

int thickness1 = ((SpinnerNumberModel)thickn.getModel()).getNumber().intValue();

如果你想更明确一点,你可以在三个点的地方添加以下内容,它会做和上面那行一样的事情

SpinnerModel model = thickn.getModel();
SpinnerNumberModel numberModel = (SpinnerNumberModel)model;
Number number = numberModel.getNumber();
int thinkness1 = number.intValue();

【讨论】:

  • 亲爱的@kirit,感谢您的帮助,但它始终采用微调器的初始值,在这种情况下为 1。我认为,问题在于它不是存储用户使用微调器输入的值。
  • 好的,尝试在您调用thickn.getValue()的行之前添加行thickn.commitEdit();
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
相关资源
最近更新 更多