gpt4 book ai didi

java - 从 JButton 创建 slider

转载 作者:行者123 更新时间:2023-11-29 05:29:03 25 4
gpt4 key购买 nike

我在 JPanel 上有 JTextFieldJButton。我想向 JButton 添加监听器,这样当我按下按钮并移动鼠标时,文本字段值开始改变(当我向右移动鼠标时增加,当我向左移动鼠标时减少)。所以它有点像 slider 。这是代码

 final JPanel panel=new JPanel();
final JTextField text = new JTextField("10");
JButton button=new JButton("f");
panel.add(text);
panel.add(button);

button.addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(final MouseEvent evt){

//here we add listener to read mouse position when mouse pressed on button
panel.addMouseListener(new MouseAdapter(){

int x1 = evt.getXOnScreen();

int x2;

@Override
public void mouseMoved(MouseEvent e){
// this method is never called
x2=e.getXOnScreen();
//increase(decrese) number in textfield by 1% for every moved pixel
double d = (x2-x1)*0.01+Double.parseDouble(text.getText());
text.setText(Double.toString(d));
x1=x2;

}


});

}
// now, when mouse released we should remove listener from panel
@Override
public void mouseReleased(final MouseEvent evt){
MouseListener[] ml = panel.getListeners(MouseListener.class);
panel.removeMouseListener(ml[0]);


}
});

问题是,永远不会调用 panelListener 的 mouseMoved 方法。我该怎么办?

最佳答案

就用

panel.addMouseMotionListener(...)

代替:

panel.addMouseListener(...)

来自 Java Docs :

public interface MouseListener: The listener interface for receiving "interesting" mouse events (press, release, click, enter, and exit) on a component. (To track mouse moves and mouse drags, use the MouseMotionListener.)

关于java - 从 JButton 创建 slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21755646/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com