如何获取 JSpinner 中所选项目的值?
我正在制作一个使用最大数量为 30 的 JSpinner 的应用程序,我应该从这个 JSpinner 中选择一个值并将一个字符串粘贴到 JTextField 中,结果将出现在 Textarea 中,当我编译时我有很多问题关于 jSpinner1State 方法,任何人都可以帮助我,因为我不知道我的问题出在哪里.这是我的方法 JSpinner 的代码:
I'm making an application that uses a JSpinner with a max number 30,I should choose a value from this JSpinner and tape a String to the JTextField and the result will appear in the Textarea,when I compile I have many problems concerning the method jSpinner1State,can any one help me because I don't know where is my problem. This is my code of the method JSpinner:
jSpinner1.addChangeListener(this);
private void jSpinner1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here:
Object sp=jSpinner1.getValue();
int i =Integer.parseInt(sp.toString() );
String targetIP=jTextField1.getText();
try{
jSpinner1StateChanged(evt);
String cmd = "tracert -h "+i+ "" +targetIP;
Process p = Runtime.getRuntime().exec(cmd);
InputStream in = p.getInputStream();
StringBuilder build = new StringBuilder();
Reader reader = new InputStreamReader(in);
char[] buffer = new char[512];
int nbRead = reader.read(buffer);
while(nbRead > 0) {
build.append(buffer, 0, nbRead);
nbRead = reader.read(buffer);
}
String response = build.toString();
jTextArea1.setText(response);
}catch(Exception e){
jTextArea1.append(e.toString()); }
}
首先,您的代码中似乎存在无限循环.在您的 jSpinner1StateChanged 函数中,您正在调用 jSpinner1StateChanged(evt)
,这将导致无限循环.
For one, it appears you have an infinite loop in your code. Inside your jSpinner1StateChanged function, you are calling jSpinner1StateChanged(evt)
, which will cause an infinite loop.
你是如何创建你的 JSpinner 的?如果您使用的是整数,则使用 SpinnerNumberModel
创建它.从微调器中获取当前值时,这将简化您的代码.
How are you creating your JSpinner? If you're using ints, then create it by using a SpinnerNumberModel
. This will simplify your code when getting the current value out of the spinner.
jSpinner1 = new JSpinner(new SpinnerNumberModel(0, 0, 30, 1));
Integer currentValue = (Integer)jSpinner1.getValue();