📄 focuseventdemo.java
字号:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class FocusEventDemo extends JFrame implements FocusListener
{
JButton btnOk,btnCancel;
JLabel lblUserName,lblPassword,lblInfo;
JTextField txtUserName;
JPasswordField pwdPassword;
JPanel pnlMain;
public FocusEventDemo()
{
pnlMain=new JPanel(new GridLayout(3,2));
lblUserName=new JLabel("用户名:");
txtUserName=new JTextField(8);
txtUserName.addFocusListener(this);
lblPassword=new JLabel("密 码:");
pwdPassword=new JPasswordField();
pwdPassword.addFocusListener(this);
btnOk=new JButton("确定");
btnOk.addFocusListener(this);
btnCancel=new JButton("取消");
getContentPane().add(pnlMain,"Center");
pnlMain.add(lblUserName);
pnlMain.add(txtUserName);
pnlMain.add(lblPassword);
pnlMain.add(pwdPassword);
pnlMain.add(btnOk);
pnlMain.add(btnCancel);
lblInfo=new JLabel("暂未获得焦点");
JPanel p2=new JPanel();
getContentPane().add(p2,"South");
p2.add(lblInfo);
setTitle("鼠标事件演示");
setVisible(true);
setSize(250,180);
}
public void focusGained(FocusEvent fe)
{
Object o=fe.getSource();
if(o==txtUserName)
{
lblInfo.setText("请输入用户名");
}
else if(o==pwdPassword)
{
lblInfo.setText("请输入密码");
}
else
lblInfo.setText("暂未获得焦点");
}
public void focusLost(FocusEvent fe)
{
Object o=fe.getSource();
if(o==btnOk)
{
lblInfo.setText("确定按钮失去焦点");
}
if(o==txtUserName)
lblInfo.setText("");
if(o==pwdPassword)
lblInfo.setText("");
}
public static void main (String args[])
{
new FocusEventDemo();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -