Java tutorial
//package com.java2s; /* * Copyright 2010, 2011 Institut Pasteur. * * This file is part of ICY. * * ICY is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ICY is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ICY. If not, see <http://www.gnu.org/licenses/>. */ import javax.swing.JSlider; import javax.swing.SwingConstants; public class Main { public static void setTickMarkers(JSlider slider) { final int min = slider.getMinimum(); final int max = slider.getMaximum(); final int delta = max - min; if (delta > 0) { final int sliderSize; if (slider.getOrientation() == SwingConstants.HORIZONTAL) sliderSize = slider.getPreferredSize().width; else sliderSize = slider.getPreferredSize().height; // adjust ticks space on slider final int majTick = findBestMajTickSpace(sliderSize, delta); slider.setMinorTickSpacing(Math.max(1, majTick / 5)); slider.setMajorTickSpacing(majTick); slider.setLabelTable(slider.createStandardLabels(slider.getMajorTickSpacing(), majTick)); } } private static int findBestMajTickSpace(int sliderSize, int delta) { final int values[] = { 1, 2, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000 }; // wanted a major tick each ~40 pixels final int wantedMajTickSpace = delta / (sliderSize / 40); int min = Integer.MAX_VALUE; int bestValue = 1; // try with our predefined values for (int value : values) { final int dx = Math.abs(value - wantedMajTickSpace); if (dx < min) { min = dx; bestValue = value; } } return bestValue; } }