[英]JButton: Simulate JButton press without the action firing
我的用例是我有一些JButton可以激活ActionListener的動作。 我還使用擊鍵來向AcionListener發出一些相同的動作命令。 當擊鍵快捷鍵觸發一個也由其中一個按鈕完成的動作時,我希望按鈕看起來好像被按下了但不能觸發事件。
所以我查看了AbstractButton API,我嘗試了一些類似setSelected的方法,但它沒有達到預期的效果。 最后我看了doCLick的方法,看看我是否可以使用刪除動作觸發部分,但這也行不通
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)
函數生成動作執行事件。 您將需要擴展此模型並為setPressed(boolean b)
函數提供自定義實現,以避免觸發操作事件。 有關更多詳細信息,請參閱此模型類的源代碼。
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());
如果希望通過左鍵單擊JButton來使用動作偵聽器,並且想要在不單擊JBUtton的情況下執行操作,則可以編寫一個單獨的公共方法來執行該操作。
就像你使用clickWithoutFiringAction方法一樣。
所以現在,你的所有動作監聽器都要執行單獨的公共方法。
final JButton jb = new JButton("Test Button");
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickWithoutFiringAction(jb);
}
});
嘿,我沒有仔細閱讀,像Sage
寫道,你必須提供setPressed()
自定義實現。
你的例子很好用。
你沒有看到效果,因為
model.setPressed(true);
之間的延遲
model.setPressed(true);
和
model.setPressed(false);
是短,只有68毫米。
增加
Thread.sleep();
值
Thread.sleep();
幾秒鍾,你會看到效果。
model.setArmed(true); model.setPressed(true); button.paintImmediately(new Rectangle(0,0, size.width, size.height)); try { Thread.sleep(68); // to short delay. } catch(InterruptedException ie) { } model.setPressed(false); model.setArmed(false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.