Code example for JSlider

Methods: setAlignmentXgetModelgetValue

0
        modelValue = Math.min(modelValue, modelMax);
        modelValue = Math.max(modelValue, modelMin);
 
//        System.out.printf("min max value -> %d %d %d%n", modelMin, modelMax, modelValue); 
 
        slider = new JSlider(JSlider.VERTICAL, modelMin, modelMax, modelValue);
        valueLabel = new JLabel() {
            @Override 
            public Dimension getPreferredSize() {
                FontMetrics fm = getFontMetrics(getFont());
                return new Dimension(fm.stringWidth("-20.00dB"), fm.getHeight());
            } 
        }; 
 
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
 
        label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        slider.setAlignmentX(JSlider.CENTER_ALIGNMENT);
        valueLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
 
        add(label);
        add(slider);
        add(valueLabel);
 
        slider.getModel().addChangeListener(this);
 
        updateValue(); 
    } 
 
    public final JSlider getSlider() {
        return slider;
    } 
 
    @Override 
    public final void stateChanged(ChangeEvent e) {
        updateValue(); 
    } 
 
    private void updateValue() { 
        int value = slider.getValue();
        valueLabel.setText(String.format(valueFormat, value / factor));
    } 
}