Search code examples
javamouseeventjprogressbar

Get value on clicking jprogressbar


I am trying to make a player in java.

Have made a seekbar using jprogressbar as shown in this link in Andrew Thompson's answer,

I have been able to add a mouselistener and detect click on jprogressbar, but how do I get the selected value of jprogressbar to which I will seek my bar to?

I tried,

progressBar.addMouseListener(new MouseAdapter() {            
    public void mouseClicked(MouseEvent e) {
           int v = progressBar.getSelectedValue();
       jlabel.setText("----"+v);
      }                                     
});

But didn't work as I expected, could not even find anything on internet.

Please help me. Thanks for your time and effort, really appreciated.


Solution

  • You would probably have to calculate the location on the JProgressBar based solely on the mouse click co-ordinates. You could essential do this:

    progressBar.addMouseListener(new MouseAdapter() {            
        public void mouseClicked(MouseEvent e) {
           int v = progressBar.getValue();
           jlabel.setText("----"+v);
    
           //Retrieves the mouse position relative to the component origin.
           int mouseX = e.getX();
    
           //Computes how far along the mouse is relative to the component width then multiply it by the progress bar's maximum value.
           int progressBarVal = (int)Math.round(((double)mouseX / (double)progressBar.getWidth()) * progressBar.getMaximum());
    
           progressBar.setValue(progressBarVal);
      }                                     
    });