views:

39

answers:

3

Hi All

I need to customize the look and feel of jslider in swing in java. I have an image of knob of jslider. I need to put this image of knob over jslider's knob which we used to select a value from the given range. I dont want to use the default knob image of jslider. Instead i want to place my own knob's image over it.

Please help me how can i do this?

Thanks Jyoti

+2  A: 

Subclass JSlider, override 'paintComponent()' and make a call to the super's implementation then draw your image in the appropriate place.

Sackers
thanks for the reply. BUt now its showing two knobs. one mine and the previous one. And my image knob is not moving also. could you please tell me how to do that?
Jyoti
For better help sooner, post an SSCCE (http://pscode.org/sscce.html) of your current code. Given it uses images, either hot-link to one on the net, or generate it in the code.
Andrew Thompson
+1  A: 

Sorry, wrong approach. Try something like this:

package java_sandbox;

import javax.imageio.ImageIO;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.plaf.basic.BasicSliderUI;

import java.awt.*;

import java.io.File;
import java.io.IOException;


public class CustomSliderKnob {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new CustomSliderKnob(); 
            }
        });
    }

    public CustomSliderKnob() {

        JFrame f = new JFrame( "Swing Slider Knob" );
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); 


        Container p = f.getContentPane();
        JSlider s = new JSlider();

        s.setUI( new mySliderUI( s ) );

        p.add( s );

        f.pack();
        f.setVisible(true);
    } 

    private class mySliderUI extends BasicSliderUI {

        Image knobImage;

        public mySliderUI( JSlider aSlider ) {

            super( aSlider );

            try {
                this.knobImage = ImageIO.read( new File( "d:\\d.jpg") );

            } catch ( IOException e ) {

                e.printStackTrace();
            }
        }
        public void paintThumb(Graphics g)  {        

            g.drawImage( this.knobImage, thumbRect.x, thumbRect.y, 8, 8, null );

        }

    }

}
Sackers
A: 

HI All,

Thanks a lot for the replies. I got the solution for my question. Its very simple.

I have done something like this:

Icon icon = new ImageIcon("slider.png");
        UIDefaults defaults = UIManager.getDefaults();
        defaults.put("Slider.horizontalThumbIcon", icon);

Thanks Jyoti

Jyoti