gpt4 book ai didi

java - JButton:在不触发 Action 的情况下模拟 JButton 按下

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

我的用例是我有一些 JButton 可以触发 ActionListener 的 Action 。我还使用击键向 AcionListener 发出一些相同的 Action 命令。当击键快捷方式触发一个也由其中一个按钮完成的 Action 时,我希望按钮看起来好像被按下但不触发事件。

所以我研究了 AbstractButton API,并尝试了其中的一些方法,例如 setSelected,但没有达到预期的效果。最后,我查看了 doCLick 方法,看看我是否可以使用删除 Action 触发部分,但这也不起作用

 367       public void doClick(int pressTime) {
368 Dimension size = getSize();
369 model.setArmed(true);
370 model.setPressed(true);
371 paintImmediately(new Rectangle(0,0, size.width, size.height));
372 try {
373 Thread.currentThread().sleep(pressTime);
374 } catch(InterruptedException ie) {
375 }
376 model.setPressed(false);
377 model.setArmed(false);
378 }

我曾想过移除所有的听众。运行 doClick 然后再次添加它们,但我认为应该可以使用更优雅的东西。

SSCE 是

public class Test {

public static void main(String[] args) throws InterruptedException{
JFrame jf = new JFrame();
jf.setLocationRelativeTo(null);
JButton jb = new JButton("Test Button");
jb.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
System.out.println("I don't want this to fire");
}
});
jf.getContentPane().add(jb);
jf.pack();
jf.setVisible(true);

Thread.sleep(1000);
clickWithoutFiringAction(jb);
}

public static void clickWithoutFiringAction(JButton button){
Dimension size = button.getSize();
ButtonModel model = button.getModel();
//I tried changing these combinations but I could not get the desired effect
model.setArmed(true);
model.setPressed(true);
button.paintImmediately(new Rectangle(0,0, size.width, size.height));
try {
Thread.sleep(68);
} catch(InterruptedException ie) {
}
model.setPressed(false);
model.setArmed(false);
}
}

最佳答案

JButton使用 DefaultButtonModel其中有 setPressed(boolean)使用 fireActionPerformed(ActionEvent e) 生成 Action 执行事件的函数功能。您将需要扩展此模型并为 setPressed(boolean b) 提供自定义实现避免 Action 事件触发的功能。详情请引用该模型类的源代码。

class CustomModel extends DefaultButtonModel
{


@Override
public void setPressed(boolean b){
if((isPressed() == b) || !isEnabled()) {
return;
}

if (b) {
stateMask |= PRESSED;
} else {
stateMask &= ~PRESSED;
}

fireStateChanged();
}

}

现在,您可以设置模型:jButton.setModel(new CustomModel());

关于java - JButton:在不触发 Action 的情况下模拟 JButton 按下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20440676/

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