我有一个从 JFileChooser 中选择音频文件的小程序。创建或更新两个 JSlider 以匹配剪辑的长度,并命名为“point A”和“point B”。A JButton 被按下,然后文件播放到 A 点。当它到达 A 点时,剪辑开始循环音频从 A 点到 B 点,并带有淡入淡出。
问题是由于显而易见的原因,我必须确保 A 点永远不会超过 B 点,但我的方法不适用于此。
添加一个在源 JSlider 更新或不更新时更新的 changelistener 是我尝试过的两件事。对于!source.getValueIsAdjusting()
,它适用于使用箭头键,但不适用于鼠标,对于source.getValueIsAdjusting()
,它以延迟的方式工作:似乎它要么比较或重置事件的值晚。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderExample extends JApplet{
private MyPanel panel;
private final Random rand = new Random();
public SliderExample() {
panel = new MyPanel();
add(panel);
}
private class MyPanel extends JPanel implements
ActionListener{
private JSlider sliderA, sliderB;
private final Timer t = new Timer(20, this);
public MyPanel()
{
super(false);
sliderA = new JSlider(JSlider.HORIZONTAL, 0, 20, 5);
sliderB = new JSlider(JSlider.HORIZONTAL, 0, 20, 15);
sliderA.setBorder(BorderFactory.createTitledBorder("Point A"));
sliderB.setBorder(BorderFactory.createTitledBorder("Point B"));
sliderA.setMajorTickSpacing(5);
sliderB.setMajorTickSpacing(5);
sliderA.setMinorTickSpacing(1);
sliderB.setMinorTickSpacing(1);
sliderA.setPaintTicks(true);
sliderB.setPaintTicks(true);
sliderA.setPaintLabels(true);
sliderB.setPaintLabels(true);
sliderA.addChangeListener(new SliderHandler());
sliderB.addChangeListener(new SliderHandler());
add(sliderA);
add(sliderB);
t.start();
}
@Override
public void actionPerformed(ActionEvent e) {
// uncomment these to see that the slider set value does work
// sliderA.setValue(rand.nextInt(sliderA.getMaximum()));
// sliderB.setValue(rand.nextInt(sliderB.getMaximum()));
int A = sliderA.getValue();
int B = sliderB.getValue();
if (A > B)
{
System.out.println("ERROR: slider A is: " + A + " and slider B is : " + B);
sliderA.setValue(B);
}
}
private class SliderHandler implements ChangeListener
{
private SliderHandler()
{
}
public void stateChanged(ChangeEvent e)
{
JSlider source = (JSlider)e.getSource();
if (!source.getValueIsAdjusting())
{
if (source == sliderA)
{
if (source.getValue() > sliderB.getValue())
{
source.setValue(sliderB.getValue());
}
}
else if (source == sliderB)
{
if (source.getValue() < sliderA.getValue())
{
source.setValue(sliderA.getValue());
}
}
}
}
}
}
}