获得点击jprogressbar的价值

时间:2013-08-09 12:42:07

标签: java mouseevent jprogressbar

我正在尝试用java创建一个播放器。

使用jprogressbar创建了一个搜索栏,如安德鲁汤普森的答案中的this link所示,

我已经能够添加一个mouselistener并检测jprogressbar上的点击,但是如何获得jprogressbar的选定值,我将向其寻找我的栏?

我试过了,

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

但是没有按照我的预期工作,甚至在互联网上找不到任何东西。

请帮帮我。感谢您的时间和精力,真的很感激。

1 个答案:

答案 0 :(得分:2)

您可能必须仅根据鼠标点击坐标来计算JProgressBar上的位置。你可以做到这一点:

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);
  }                                     
});