gpt4 book ai didi

java - 设置 swing JSlider 和 JTextField 的刻度行为

转载 作者:行者123 更新时间:2023-11-30 07:15:39 25 4
gpt4 key购买 nike

这是我的图形用户界面:

enter image description here

下面是一个 SSCCE,它将产生这个。 JSlider 连接到 JTextField,显示 0 到 100 之间的值。

我已设置以下内容以使其以 10 为间隔停止。它有效,但文本字段在拖动时仍会显示 10 秒(如 73)之间的值,然后在我放开 slider 时对其进行调整。有没有办法只显示十位,即使在拖动时也是如此?

js.setMinorTickSpacing(10);
js.setSnapToTicks(true);

中南合作:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.event.*;
import net.miginfocom.swing.MigLayout;

public class SSCCE {
public static void main(String[] args) {
JFrame frame = new JFrame("SSCCE JSlider + JTextField");
JPanel panel = new JPanel(new MigLayout("", "[200!][100!]", ""));

final JSlider js = new JSlider();
final JFormattedTextField tf = new JFormattedTextField(NumberFormat.getNumberInstance());

js.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
tf.setText(String.valueOf(js.getValue()));
}
});
tf.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent ke) {
String typed = tf.getText();
js.setValue(0);
if (!typed.matches("\\d+")) {
return;
}
int value = Integer.parseInt(typed);
js.setValue(value);
}
});
js.setMinorTickSpacing(10);
js.setSnapToTicks(true);

panel.add(js);
panel.add(tf, "grow");
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}

最佳答案

It works, but the textfield will still show values between the 10s (Like 73) when dragging, and then adjust it when i let go of the slider. Is there a way to ONLY show tens, even when dragging?

只需将当前 JSlider 值四舍五入到最接近的 10,然后将 JTextField 设置为该数字:

 js.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {

if(js.getValueIsAdjusting()) {//slider value is still being adjusted
int num=(int)(Math.rint((double) js.getValue() / 10) * 10);//round to nearest 10
tf.setText(String.valueOf(num));//set textfield with value of nearest 10
} else {//slider value has been set/no adjustments happenening
tf.setText(String.valueOf(js.getValue()));
}

}
});

也可以阅读 Concurrency in Swing ,特别是关于 Event Dispatch thread (EDT) ,这需要我们通过 SwingUtilities.invokeXXX 在 EDT 上创建和操作所有 Swing 组件 block :

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//create/manipulate UI, components etc here
}
});

关于java - 设置 swing JSlider 和 JTextField 的刻度行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17565667/

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