Hi All,
I need to customize the knob of JSlider. I need to put my own knob's image over default knob of Jslider. The problem is that currently two knobs are coming in response. One my own knob and second the default knob. Please tell me how i can i hide the default knob or any other solution.
Below code is used to do so.
public class ImageTest {
JSlider slider;
JLabel label;
public ImageTest()
{
JPanel panel = new BackgroundPanel();
slider = new BackgroundSlider();
slider.setMaximum(300);
slider.setMinimum(0);
slider.setValue(50);
slider.setExtent(10);
slider.addChangeListener(new MyChangeAction());
label = new JLabel("50");
panel.setLayout(new GridBagLayout());
panel.setSize(797,402);
slider.setOpaque(false);
slider.setPaintTrack(false);
label.setOpaque(false);
slider.setPreferredSize(new Dimension(340, 20));
GridBagConstraints gridBagConstraintsSlider = new GridBagConstraints();
gridBagConstraintsSlider.gridy = 0;
gridBagConstraintsSlider.gridx = 0;
gridBagConstraintsSlider.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraintsSlider.insets = new Insets(0, 283, 260, 0);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.gridx = 1;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new Insets(0, 50, 240, 0);
panel.add(slider, gridBagConstraintsSlider);
panel.add(label, gridBagConstraints);
JFrame frame = new JFrame();
frame.getContentPane().add(panel);
frame.setSize(797,402);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
WindowUtil.locateCenter(frame);
}
public static void main(String[] args) {
ImageTest im= new ImageTest();
}
public class MyChangeAction implements ChangeListener{
public void stateChanged(ChangeEvent ce){
int value = slider.getValue();
String str = Integer.toString(value);
label.setText(str);
if(value==300)
{
label.setText("Max");
}
}
}
}
class BackgroundSlider extends JSlider
{
Image image;
public BackgroundSlider()
{
try
{
image = javax.imageio.ImageIO.read(new File("slider.png"));
}
catch (Exception e) { /*handled in paintComponent()*/ }
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image != null)
g.drawImage(image, this.getValue(),(int)this.getAlignmentY(),10,20,this);
g.setColor(Color.RED);
//draw a centered horizontal line
g.drawRect(15,this.getHeight()-1,this.getValue(),this.getHeight()+2);
g.fillRect(15,this.getHeight()-1,this.getValue(),this.getHeight()+2);
}
}
Thanks Jyoti