Google Tag Manager

Showing posts with label JSlider. Show all posts
Showing posts with label JSlider. Show all posts

2019/02/27

aterai

Limit the movable range of JSlider's value

Code

public static final int MAXI = 80;
public static final int MINI = 40;

private static class MetalDragLimitedSliderUI extends MetalSliderUI {
  @Override protected TrackListener createTrackListener(JSlider slider) {
    return new TrackListener() {
      @Override public void mouseDragged(MouseEvent e) {
        // case HORIZONTAL:
        int halfThumbWidth = thumbRect.width / 2;
        int thumbLeft = e.getX() - offset;
        int maxPos = xPositionForValue(MAXI) - halfThumbWidth;
        int minPos = xPositionForValue(MINI) - halfThumbWidth;
        if (thumbLeft > maxPos) {
          e.translatePoint(maxPos + offset - e.getX(), 0);
        } else if (thumbLeft < minPos) {
          e.translatePoint(minPos + offset - e.getX(), 0);
        }
        super.mouseDragged(e);
      }
    };
  }
}

private static JSlider makeSilder(String title) {
  JSlider slider = new JSlider(0, 100, 40);
  slider.setBorder(BorderFactory.createTitledBorder(title));
  slider.setMajorTickSpacing(10);
  slider.setPaintTicks(true);
  slider.setPaintLabels(true);
  Dictionary<?, ?> dictionary = slider.getLabelTable();
  if (Objects.nonNull(dictionary)) {
    Enumeration<?> elements = dictionary.elements();
    while (elements.hasMoreElements()) {
      JLabel label = (JLabel) elements.nextElement();
      int v = Integer.parseInt(label.getText());
      if (v > MAXI || v < MINI) {
        label.setForeground(Color.RED);
      }
    }
  }
  slider.getModel().addChangeListener(e -> {
    BoundedRangeModel m = (BoundedRangeModel) e.getSource();
    if (m.getValue() > MAXI) {
      m.setValue(MAXI);
    } else if (m.getValue() < MINI) {
      m.setValue(MINI);
    }
  });
  return slider;
}

References

2016/06/27

aterai

Change the color of the label represents the current value of a JSlider

Code

slider.getModel().addChangeListener(new ChangeListener() {
  private int prev = -1;
  private void resetForeground(Object o, Color c) {
    if (o instanceof Component) {
      ((Component) o).setForeground(c);
    }
  }
  @Override public void stateChanged(ChangeEvent e) {
    BoundedRangeModel m = (BoundedRangeModel) e.getSource();
    int i = m.getValue();
    if ((slider.getMajorTickSpacing() == 0 ||
         i % slider.getMajorTickSpacing() == 0) && i != prev) {
      Dictionary dictionary = slider.getLabelTable();
      resetForeground(dictionary.get(i), Color.RED);
      resetForeground(dictionary.get(prev), Color.BLACK);
      slider.repaint();
      prev = i;
    }
  }
});

References

2015/10/30

aterai

Display tooltip while dragging JSlider thumb

Code

class SliderPopupListener extends MouseAdapter {
  private final JWindow toolTip = new JWindow();
  private final JLabel label = new JLabel("", SwingConstants.CENTER);
  private final Dimension size = new Dimension(30, 20);
  private int prevValue = -1;

  protected SliderPopupListener() {
    super();
    label.setOpaque(false);
    label.setBackground(UIManager.getColor("ToolTip.background"));
    label.setBorder(UIManager.getBorder("ToolTip.border"));
    toolTip.add(label);
    toolTip.setSize(size);
  }
  protected void updateToolTip(MouseEvent me) {
    JSlider slider = (JSlider) me.getComponent();
    int intValue = (int) slider.getValue();
    if (prevValue != intValue) {
      label.setText(String.format("%03d", slider.getValue()));
      Point pt = me.getPoint();
      pt.y = -size.height;
      SwingUtilities.convertPointToScreen(pt, me.getComponent());
      pt.translate(-size.width / 2, 0);
      toolTip.setLocation(pt);
    }
    prevValue = intValue;
  }
  @Override public void mouseDragged(MouseEvent me) {
    updateToolTip(me);
  }
  @Override public void mousePressed(MouseEvent me) {
    if (UIManager.getBoolean("Slider.onlyLeftMouseButtonDrag")
        && SwingUtilities.isLeftMouseButton(me)) {
      toolTip.setVisible(true);
      updateToolTip(me);
    }
  }
  @Override public void mouseReleased(MouseEvent me) {
    toolTip.setVisible(false);
  }
  @Override public void mouseWheelMoved(MouseWheelEvent e) {
    JSlider s = (JSlider) e.getComponent();
    int i = (int) s.getValue() - e.getWheelRotation();
    BoundedRangeModel m = s.getModel();
    s.setValue(Math.min(Math.max(i, m.getMinimum()), m.getMaximum()));
  }
}

References

2014/06/02

aterai

How to create a circular progress component

Code

class ProgressCircleUI extends BasicProgressBarUI {
  @Override public Dimension getPreferredSize(JComponent c) {
    Dimension d = super.getPreferredSize(c);
    int v = Math.max(d.width, d.height);
    d.setSize(v, v);
    return d;
  }
  @Override public void paint(Graphics g, JComponent c) {
    Insets b = progressBar.getInsets(); // area for border
    int barRectWidth  = progressBar.getWidth()  - b.right - b.left;
    int barRectHeight = progressBar.getHeight() - b.top - b.bottom;
    if (barRectWidth <= 0 || barRectHeight <= 0) {
      return;
    }

    // draw the cells
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(progressBar.getForeground());
    double degree = 360 * progressBar.getPercentComplete();
    double sz = Math.min(barRectWidth, barRectHeight);
    double cx = b.left + barRectWidth  * .5;
    double cy = b.top  + barRectHeight * .5;
    double or = sz * .5;
    double ir = or * .5; //or - 20;
    Shape inner = new Ellipse2D.Double(cx - ir, cy - ir, ir * 2, ir * 2);
    Shape outer = new Arc2D.Double(
        cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
    Area area = new Area(outer);
    area.subtract(new Area(inner));
    g2.fill(area);
    g2.dispose();

    // Deal with possible text painting
    if (progressBar.isStringPainted()) {
      paintString(g, b.left, b.top, barRectWidth, barRectHeight, 0, b);
    }
  }
}
import java.awt.*;
import javax.swing.*;

public class CircularProgressTest {
  public JComponent makeUI() {
    JProgressBar progress = new JProgressBar();
    // use JProgressBar#setUI(...) method
    progress.setUI(new ProgressCircleUI());
    progress.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));
    progress.setStringPainted(true);
    progress.setFont(progress.getFont().deriveFont(24f));
    progress.setForeground(Color.ORANGE);

    (new Timer(50, e -> {
      int iv = Math.min(100, progress.getValue() + 1);
      progress.setValue(iv);
    })).start();

    JPanel p = new JPanel();
    p.add(progress);
    return p;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new CircularProgressTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}

References

2011/06/27

aterai

Gradient translucent track JSlider

Code

UIManager.put("Slider.horizontalThumbIcon", new Icon() {
  @Override public void paintIcon(Component c, Graphics g, int x, int y) {}
  @Override public int getIconWidth()  { return 15; }
  @Override public int getIconHeight() { return 64; }
});
UIManager.put("Slider.trackWidth", 64);
UIManager.put("Slider.majorTickLength", 6);

JSlider slider = makeSlider();
slider.setUI(new MetalSliderUI() {
  int[] pallet = makeGradientPallet();
  @Override public void paintTrack(Graphics g) {
    //Color trackColor = !slider.isEnabled()
    //  ? MetalLookAndFeel.getControlShadow() : slider.getForeground();
    boolean leftToRight = true; //MetalUtils.isLeftToRight(slider);
    Color controlDarkShadow = Color.GRAY;
    Color controlHighlight = new Color(200,255,200);
    Color controlShadow = new Color(0,100,0);

    g.translate( trackRect.x, trackRect.y );

    int trackLeft = 0;
    int trackTop = 0;
    int trackRight = 0;
    int trackBottom = 0;

    // Draw the track
    if(slider.getOrientation() == JSlider.HORIZONTAL) {
      trackBottom = (trackRect.height - 1) - getThumbOverhang();
      trackTop = trackBottom - (getTrackWidth() - 1);
      trackRight = trackRect.width - 1;
    }else{
      if(leftToRight) {
        trackLeft = (trackRect.width - getThumbOverhang()) - getTrackWidth();
        trackRight = (trackRect.width - getThumbOverhang()) - 1;
      }else{
        trackLeft = getThumbOverhang();
        trackRight = getThumbOverhang() + getTrackWidth() - 1;
      }
      trackBottom = trackRect.height - 1;
    }

    if(slider.isEnabled()) {
      g.setColor(controlDarkShadow);
      g.drawRect(trackLeft, trackTop,
                 (trackRight - trackLeft) - 1, (trackBottom - trackTop) - 1);

      g.setColor(controlHighlight);
      g.drawLine(trackLeft + 1, trackBottom, trackRight, trackBottom);
      g.drawLine(trackRight, trackTop + 1, trackRight, trackBottom);

      g.setColor(controlShadow);
      g.drawLine(trackLeft + 1, trackTop + 1, trackRight - 2, trackTop + 1);
      g.drawLine(trackLeft + 1, trackTop + 1, trackLeft + 1, trackBottom - 2);
    } else {
      g.setColor(controlShadow);
      g.drawRect(trackLeft, trackTop,
                 (trackRight - trackLeft) - 1, (trackBottom - trackTop) - 1);
    }

    // Draw the fill
    int middleOfThumb = 0;
    int fillTop = 0;
    int fillLeft = 0;
    int fillBottom = 0;
    int fillRight = 0;

    if(slider.getOrientation() == JSlider.HORIZONTAL) {
      middleOfThumb = thumbRect.x + (thumbRect.width / 2);
      middleOfThumb -= trackRect.x; // To compensate for the g.translate()
      fillTop = !slider.isEnabled() ? trackTop : trackTop + 1;
      fillBottom = !slider.isEnabled() ? trackBottom - 1 : trackBottom - 2;

      if(!drawInverted()) {
        fillLeft = !slider.isEnabled() ? trackLeft : trackLeft + 1;
        fillRight = middleOfThumb;
      }else{
        fillLeft = middleOfThumb;
        fillRight = !slider.isEnabled() ? trackRight - 1 : trackRight - 2;
      }
    }else{
      middleOfThumb = thumbRect.y + (thumbRect.height / 2);
      middleOfThumb -= trackRect.y; // To compensate for the g.translate()
      fillLeft = !slider.isEnabled() ? trackLeft : trackLeft + 1;
      fillRight = !slider.isEnabled() ? trackRight - 1 : trackRight - 2;

      if(!drawInverted()) {
        fillTop = middleOfThumb;
        fillBottom = !slider.isEnabled() ? trackBottom - 1 : trackBottom - 2;
      }else{
        fillTop = !slider.isEnabled() ? trackTop : trackTop + 1;
        fillBottom = middleOfThumb;
      }
    }

    if(slider.isEnabled()) {
      g.setColor(slider.getBackground());
      g.drawLine(fillLeft, fillTop, fillRight, fillTop );
      g.drawLine(fillLeft, fillTop, fillLeft, fillBottom );

      double x = (fillRight - fillLeft) / (double)(trackRight - trackLeft);
      g.setColor(getColorFromPallet(pallet, x));
      g.fillRect(fillLeft+1,fillTop+1,fillRight-fillLeft,fillBottom-fillTop);
    }else{
      g.setColor(controlShadow);
      g.fillRect(fillLeft,fillTop,fillRight-fillLeft,trackBottom-trackTop);
    }

    int yy = trackTop + (trackBottom - trackTop) /2;
    for(int i=10;i>=0;i--) {
      g.setColor( new Color(1f,1f,1f,i*0.07f) );
      g.drawLine( trackLeft+2, yy, (trackRight - trackLeft), yy );
      yy--;
    }
    g.translate(-trackRect.x, -trackRect.y);
  }
});
private static int[] makeGradientPallet() {
  BufferedImage image = new BufferedImage(100, 1, BufferedImage.TYPE_INT_RGB);
  Graphics2D g2  = image.createGraphics();
  Point2D start  = new Point2D.Float(0f, 0f);
  Point2D end  = new Point2D.Float(99f, 0f);
  float[] dist   = {0.0f, 0.5f, 1.0f};
  Color[] colors = { Color.RED, Color.YELLOW, Color.GREEN };
  g2.setPaint(new LinearGradientPaint(start, end, dist, colors));
  g2.fillRect(0, 0, 100, 1);
  int width  = image.getWidth(null);
  int[] pallet = new int[width];
  PixelGrabber pg = new PixelGrabber(image, 0, 0, width, 1, pallet, 0, width);
  try{
    pg.grabPixels();
  }catch(Exception e) {
    e.printStackTrace();
  }
  return pallet;
}
private static Color getColorFromPallet(int[] pallet, float x) {
  int i = (int)(pallet.length * x);
  int max = pallet.length-1;
  int index = i<0?0:i>max?max:i;
  int pix = pallet[index] & 0x00ffffff | (0x64 << 24);
  return new Color(pix, true);
}

References

2009/12/21

aterai

snap to ticks drag JSlider

Code

slider.setUI(new MetalSliderUI() {
  protected TrackListener createTrackListener(final JSlider slider) {
    return new TrackListener() {
      public void mouseDragged(MouseEvent e) {
        if(!slider.getSnapToTicks() || slider.getMajorTickSpacing()==0) {
          super.mouseDragged(e);
          return;
        }
        //case JSlider.HORIZONTAL:
        int halfThumbWidth    = thumbRect.width / 2;
        int trackLength = trackRect.width;
        int trackLeft  = trackRect.x-halfThumbWidth;
        int trackRight = trackRect.x+(trackRect.width-1)+halfThumbWidth;
        int xPos = e.getX();
        int snappedPos = xPos;
        if (xPos < = trackLeft) {
          snappedPos = trackLeft;
        } else if (xPos > = trackRight) {
          snappedPos = trackRight;
        } else {
          //int tickSpacing = slider.getMajorTickSpacing();
          //float actualPixelsForOneTick = trackLength * tickSpacing
          //                                 / (float)slider.getMaximum();
          // a problem if you choose to set a negative MINIMUM for
          // the JSlider; the calculated drag-positions are wrong.
          // Fixed by bobndrew:
          int possibleTickPositions=slider.getMaximum()-slider.getMinimum();
          int tickSpacing = (slider.getMinorTickSpacing()==0)
                            ? slider.getMajorTickSpacing()
                            : slider.getMinorTickSpacing();
          float actualPixelsForOneTick = trackLength * tickSpacing
                                         / (float)possibleTickPositions;
          xPos -= trackLeft;
          snappedPos=(int)(
            (Math.round(xPos/actualPixelsForOneTick)*actualPixelsForOneTick)+0.5)
            +trackLeft;
          offset = 0;
        }
        MouseEvent me = new MouseEvent(
          e.getComponent(), e.getID(), e.getWhen(), e.getModifiers(),
          snappedPos, e.getY(),
          e.getXOnScreen(), e.getYOnScreen(),
          e.getClickCount(), e.isPopupTrigger(), e.getButton());
        super.mouseDragged(me);
      }
    };
  }
});

References

2009/11/30

aterai

Jump to clicked position JSlider

Code

slider.setUI(new MetalSliderUI() {
  @Override protected TrackListener createTrackListener(JSlider slider) {
    return new TrackListener() {
      @Override public void mousePressed(MouseEvent e) {
        if (UIManager.getBoolean("Slider.onlyLeftMouseButtonDrag")
              && SwingUtilities.isLeftMouseButton(e)) {
          JSlider slider = (JSlider) e.getComponent();
          switch (slider.getOrientation()) {
          case SwingConstants.VERTICAL:
            slider.setValue(valueForYPosition(e.getY()));
            break;
          case SwingConstants.HORIZONTAL:
            slider.setValue(valueForXPosition(e.getX()));
            break;
          default:
            throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
          }
          super.mousePressed(e); //isDragging = true;
          super.mouseDragged(e);
        } else {
          super.mousePressed(e);
        }
      }
      @Override public boolean shouldScroll(int direction) {
        return false;
      }
    };
  }
});

References

2009/02/26

aterai

Use JScrollBar as JSlider

Code

int step   = 5;
int extent = 20;
int min    = 0;
int max    = extent*10; //200
int value  = 50;
final JScrollBar scrollbar = new JScrollBar(
            JScrollBar.HORIZONTAL, value, extent, min, max+extent);
scrollbar.setUnitIncrement(step);
scrollbar.getModel().addChangeListener(new ChangeListener(){
  public void stateChanged(javax.swing.event.ChangeEvent e) {
    BoundedRangeModel m = (BoundedRangeModel)e.getSource();
    spinner.setValue(m.getValue());
  }
});
final JSpinner spinner = new JSpinner(
            new SpinnerNumberModel(value, min, max, step));
//...

References