Search code examples
javaeclipsejscrollbar

JScrollBar: the knob is not visible with small max values


I want to create a horizontal scrollbar whith max value set to 2 (it should allow only to choose 0, 1 or 2 as a value), but the knob is invisible if the value is smaller than 11.

    scrlLineDist = new JScrollBar();
    scrlLineDist.setBlockIncrement(1);
    scrlLineDist.addAdjustmentListener(new AdjustmentListener() {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            System.out.println(scrlLineDist.getValue());
        }
    });
    GridBagConstraints gbc_scrlLineDist = new GridBagConstraints();
    gbc_scrlLineDist.insets = new Insets(0, 0, 5, 0);
    gbc_scrlLineDist.fill = GridBagConstraints.HORIZONTAL;
    gbc_scrlLineDist.gridx = 0;
    gbc_scrlLineDist.gridy = 3;
    panel_4.add(scrlLineDist, gbc_scrlLineDist);
    scrlLineDist.setMaximum(2);
    scrlLineDist.setToolTipText("");
    scrlLineDist.setOrientation(JScrollBar.HORIZONTAL);

When I change the maximum value to 12, it works the way I want (visible knob, values [0,2]). Why is this happening?

    scrlLineDist = new JScrollBar();
    scrlLineDist.setBlockIncrement(1);
    scrlLineDist.addAdjustmentListener(new AdjustmentListener() {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            System.out.println(scrlLineDist.getValue());
        }
    });
    GridBagConstraints gbc_scrlLineDist = new GridBagConstraints();
    gbc_scrlLineDist.insets = new Insets(0, 0, 5, 0);
    gbc_scrlLineDist.fill = GridBagConstraints.HORIZONTAL;
    gbc_scrlLineDist.gridx = 0;
    gbc_scrlLineDist.gridy = 3;
    panel_4.add(scrlLineDist, gbc_scrlLineDist);
    scrlLineDist.setMaximum(12);
    scrlLineDist.setToolTipText("");
    scrlLineDist.setOrientation(JScrollBar.HORIZONTAL);

Solution

  • What you are looking for is probably a JSlider, not a JScrollbar.

    // orientation, min, max, initial value
    final JSlider slider = new JSlider(SwingConstants.HORIZONTAL, 0, 2, 1);
    slider.setSnapToTicks(true); // only allow 0, 1, 2 and not in between
    slider.setPaintTicks(true); // paint ticks at tick spacing interval
    slider.setMajorTickSpacing(1); // set interval to 1
    slider.setPaintLabels(true); // show labels on ticks
    

    Instead of a AdjustmentListener, add a ChangeListener to your slider, like so:

    slider.addChangeListener(new ChangeListener() {
    
        @Override
        public void stateChanged(ChangeEvent e) {
            // only output when value is set (when the mouse is released from the knob)
            // remove this if statement if you would like output whenever the knob is moved
            if(!slider.getValueIsAdjusting()) {
                System.out.println(slider.getValue());
            }
        }
    
    });    
    

    For more information about JSliders, and an official tutorial, check out The Java™ Tutorials - How to Use Sliders