how to put image on jslilder's knob of swing in java?
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 开发者_如何学Pythonput 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
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 );
}
}
}
Subclass JSlider, override 'paintComponent()' and make a call to the super's implementation then draw your image in the appropriate place.
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
精彩评论