gpt4 book ai didi

java - 检查是否选择了 JTextfield

转载 作者:行者123 更新时间:2023-12-03 22:08:53 26 4
gpt4 key购买 nike

是否可以检查 jtextfield 是否已被选择/取消选择(即已单击文本字段并且光标现在位于该字段内)?

//编辑
感谢下面的帮助,这里是一个工作示例

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class test extends JFrame {

private static JPanel panel = new JPanel();
private static JTextField textField = new JTextField(20);
private static JTextField textField2 = new JTextField(20);

public test() {
panel.add(textField);
panel.add(textField2);
this.add(panel);
}

public static void main(String args[]) {

test frame = new test();
frame.setVisible(true);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

textField.addFocusListener(new FocusListener() {

@Override
public void focusGained(FocusEvent e) {
System.out.println("selected");
}

@Override
public void focusLost(FocusEvent e) {
System.out.println("de-selected");
}
});
}
}

最佳答案

您将需要使用 focusGainedfocusLost事件以查看它何时被选择,何时被取消选择(即获得/失去焦点)。

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JTextField;

public class Main {

public static void main(String args[]) {
final JTextField textField = new JTextField();
textField.addFocusListener(new FocusListener() {

@Override
public void focusGained(FocusEvent e) {
//Your code here
}

@Override
public void focusLost(FocusEvent e) {
//Your code here
}
});

}
}

关于java - 检查是否选择了 JTextfield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8292773/

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