gpt4 book ai didi

swing - doClick 一个不可见的按钮

转载 作者:行者123 更新时间:2023-12-01 10:09:06 25 4
gpt4 key购买 nike

我可以在按钮不可见后调用 doClick 吗?
喜欢:

StopBtn.setVisible( false );
StopBtn.doClick();

doClick() 还会继续工作吗?

最佳答案

发现这一点的最简单方法当然是测试它(例如,如果您担心 Oracle 的那些人会改变行为,则在单元测试中)

@Test
public void clickOnInvisibleButton(){
JButton button = new JButton( "test button" );
button.setVisible( false );
final boolean[] buttonClicked = new boolean[]{false};
button.addActionListener( new ActionListener(){
@Override
public void actionPerformed( ActionEvent e ){
buttonClicked[0] = true;
}
});
button.doClick();
assertTrue( "Button has not been clicked", buttonClicked[0] );
}

否则,您可以查看该方法的源代码

public void doClick(int pressTime) {
Dimension size = getSize();
model.setArmed(true);
model.setPressed(true);
paintImmediately(new Rectangle(0,0, size.width, size.height));
try {
Thread.currentThread().sleep(pressTime);
} catch(InterruptedException ie) {
}
model.setPressed(false);
model.setArmed(false);
}

在那里你没有找到可见性检查。进一步看(例如在模型的 setPressed 方法中),您会发现检查了 enabled 状态,但清楚地看到没有检查可见性当下。您还会看到触发了 ActionEvent,这将触发按钮的 actionPerformed 方法

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

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

if(!isPressed() && isArmed()) {
int modifiers = 0;
AWTEvent currentEvent = EventQueue.getCurrentEvent();
if (currentEvent instanceof InputEvent) {
modifiers = ((InputEvent)currentEvent).getModifiers();
} else if (currentEvent instanceof ActionEvent) {
modifiers = ((ActionEvent)currentEvent).getModifiers();
}
fireActionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
getActionCommand(),
EventQueue.getMostRecentEventTime(),
modifiers));
}

fireStateChanged();
}

关于swing - doClick 一个不可见的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149378/

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