本文介绍了Java:链接JSlider和JTextfield以获取浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
链接JSlider和JTextField的最佳和最简单的方法是什么,如果一个更改,另一个也会更新,但没有递归循环?
what is the best and easiest way to link a JSlider and a JTextField so that if one changes, the other gets updated too, but there is no recursive loop?
谢谢!
推荐答案
这是一个快速而又肮脏的演示:
Here's a quick and dirty demo:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame();
final JTextField text = new JTextField(20);
final JSlider slider = new JSlider(0, 100, 0);
slider.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e) {
text.setText(String.valueOf(slider.getValue()));
}
});
text.addKeyListener(new KeyAdapter(){
@Override
public void keyReleased(KeyEvent ke) {
String typed = text.getText();
slider.setValue(0);
if(!typed.matches("\\d+") || typed.length() > 3) {
return;
}
int value = Integer.parseInt(typed);
slider.setValue(value);
}
});
frame.setLayout(new BorderLayout());
frame.add(text, BorderLayout.NORTH);
frame.add(slider, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
编辑
如果你想使用浮点数(如标题所示),你可以像这样扩展JSlider类:
And if you want to use floats (as the title suggests), you could extends the JSlider class like this:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
final DecimalFormat df = new DecimalFormat("0.####");
final JFrame frame = new JFrame();
final JTextField text = new JTextField(20);
final DoubleJSlider slider = new DoubleJSlider(0, 100, 0, 1000);
slider.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e) {
text.setText(df.format(slider.getScaledValue()));
}
});
text.addKeyListener(new KeyAdapter(){
@Override
public void keyReleased(KeyEvent ke) {
String typed = text.getText();
slider.setValue(0);
if(!typed.matches("\\d+(\\.\\d*)?")) {
return;
}
double value = Double.parseDouble(typed)*slider.scale;
slider.setValue((int)value);
}
});
frame.setLayout(new BorderLayout());
frame.add(text, BorderLayout.NORTH);
frame.add(slider, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
}
}
class DoubleJSlider extends JSlider {
final int scale;
public DoubleJSlider(int min, int max, int value, int scale) {
super(min, max, value);
this.scale = scale;
}
public double getScaledValue() {
return ((double)super.getValue()) / this.scale;
}
}
上面的例子表示0到0.1之间的间隔100步。
The example above denotes the interval between 0 and 0.1 in 100 steps.
这(又一次)只是一个快速而又肮脏的例子,但可能会帮助你。
This (again) is just a quick and dirty example, but might help you on your way.
这篇关于Java:链接JSlider和JTextfield以获取浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!