我有N個JSliders的列表(N沒有程序上的變化,只是因爲我增加更多的功能。目前,N等於4)。所有滑塊值的總和必須等於100.當一個滑塊移動時,滑塊的其餘部分將進行調整。當滑塊被改變每個滑動器具有範圍從0到100。的Java JSlider的精度問題
值目前我使用這種邏輯(僞代碼):
newValue = currentSlider.getValue
otherSliders = allSliders sans currentSlider
othersValue = summation of otherSliders values
properOthersValue = 100 - newValue
ratio = properOthersValue/othersValue
for slider in otherSlider
slider.value = slider.getValue * ratio
與此設置的問題是滑塊的值存儲爲整數。所以當我調整滑塊時,我會遇到精度問題:滑塊會根據比率值抽動或者根本不動。另外,總價值並不總是加起來100
有沒有人有沒有創建支持浮點或雙精度全新JSlider類的解決這個問題呢?
如果你想,我想要的行爲的一個例子,請訪問:Humble Indie Bundle並滾動到頁面底部。
謝謝
p.s.將該值乘以比率可以讓用戶將值鎖定爲0.但是,當4個滑塊中的3個爲0,第4個滑塊爲100時,我不確定該做什麼,並且將第4個滑塊向下移動。使用上面的邏輯,3個滑塊的值爲0,第4個滑塊移動到用戶放置的位置,總數小於100,這是不正確的行爲。
EDIT
這裏是SSCCE:
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.util.LinkedList;
public class SliderDemo
{
static LinkedList<JSlider> sliders = new LinkedList<JSlider>();
static class SliderListener implements ChangeListener
{
boolean updating = false;
public void stateChanged(ChangeEvent e)
{
if (updating) return;
updating = true;
JSlider source = (JSlider)e.getSource();
int newValue = source.getValue();
LinkedList<JSlider> otherSliders = new LinkedList<JSlider>(sliders);
otherSliders.remove(source);
int otherValue = 0;
for (JSlider slider : otherSliders)
{
otherValue += slider.getValue();
}
int properValue = 100 - newValue;
double ratio = properValue/(double)otherValue;
for (JSlider slider : otherSliders)
{
int currentValue = slider.getValue();
int updatedValue = (int) (currentValue * ratio);
slider.setValue(updatedValue);
}
int total = 0;
for (JSlider slider : sliders)
{
total += slider.getValue();
}
System.out.println("Total = " + total);
updating = false;
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("SliderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = frame.getContentPane();
JPanel sliderPanel = new JPanel(new GridBagLayout());
container.add(sliderPanel);
SliderListener listener = new SliderListener();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
int sliderCount = 4;
int initial = 100/sliderCount;
for (int i = 0; i < sliderCount; i++)
{
gbc.gridy = i;
JSlider slider = new JSlider(0, 100, initial);
slider.addChangeListener(listener);
slider.setMajorTickSpacing(50);
slider.setPaintTicks(true);
sliders.add(slider);
sliderPanel.add(slider, gbc);
}
frame.pack();
frame.setVisible(true);
}
}
最好的辦法是建立一個[SSCCE(HTTP:// SSCCE .org)並在這裏發佈代碼。請在回覆之前閱讀鏈接,因爲我們絕對不想看到您的整個程序。 –
請參閱下面的答案中的示例代碼。在Swing中, –
,答案始終是一個自定義模型。儘管Slider並沒有像它應該那樣承認它:http://stackoverflow.com/questions/7468314/linked-jsliders-with-maximum-combined-value – kleopatra