gpt4 book ai didi

java - 按 JButton 时将光标转移到 JTextField

转载 作者:行者123 更新时间:2023-12-01 10:05:43 26 4
gpt4 key购买 nike

当我单击“预览页面”按钮时,光标应移动到开始位置 (txtStartPosition)。下面是我编写的代码,但不知何故它不起作用。

    btnPreviewPage = new JButton("Preview Single");
btnPreviewPage.setFocusable(false);
btnPreviewPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtStartPosition.setCaretPosition(txtStartPosition.getCaretPosition() - 1);
new UIPreviewPage().execute();
}
});
panel.add(btnPreviewPage, "cell 1 18,alignx right");

enter image description here

最佳答案

您需要执行JTextField.requestFocus();或者,更首选的JTextField.requestFocusInWindow();

https://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#requestFocus()

public void requestFocus() Requests that this Component gets the input focus. Refer to Component.requestFocus() for a complete description of this method. Note that the use of this method is discouraged because its behavior is platform dependent. Instead we recommend the use of requestFocusInWindow(). If you would like more information on focus, see How to Use the Focus Subsystem, a section in The Java Tutorial.

Overrides:
requestFocus in class Component
Since:
1.4
See Also:

Component.requestFocusInWindow(), Component.requestFocusInWindow(boolean)
<小时/>

使用你的代码应该是

    tnPreviewPage = new JButton("Preview Single");
btnPreviewPage.setFocusable(false);
btnPreviewPage.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {

//Add YourJTextField.requestFocusInWindow() here, but not sure if the other information is needed
txtStartPosition.setCaretPosition(txtStartPosition.getCaretPosition() - 1);
new UIPreviewPage().execute();
}
});
panel.add(btnPreviewPage, "cell 1 18,alignx right");

关于java - 按 JButton 时将光标转移到 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490953/

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