62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.TextField;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class DemoFrame_3 extends JFrame {
private static final long serialVersionUID = -4153854902587618289L;
public static void main(String[] args) {
// TODO Auto-generated method stub
new DemoFrame_3().setVisible(true);
}
private TextField text1;
public DemoFrame_3() {
// TODO Auto-generated constructor stub
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setLayout(null);
text1 = new TextField();
text1.setSize(150, 25);
text1.setLocation(10, 10);
add(text1);
text1.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
}
@Override
public void focusLost(FocusEvent e) {
String txt = text1.getText();
if (txt.equals("")) {
JOptionPane.showMessageDialog(DemoFrame_3.this, "对不起,这是必选字段,请输入。");
text1.requestFocusInWindow(); // 设置焦点为长度有误的文本框中
text1.setText(null);
} else {
JOptionPane.showMessageDialog(DemoFrame_3.this, "您输入的是:" + txt);
}
}
});
JButton button = new JButton("确定");
button.setSize(75, 25);
button.setLocation(80, 50);
add(button);
}
}