package Collection;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class Windowfa extends JFrame{
private JPanel contentPane;
private JLabel lblTip;
private JLabel lblTight;//声明窗体中的组件
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
Windowfa frame = new Windowfa();
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public Windowfa(){
setResizable(false);
setTitle("焦点事件监听");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(100, 100, 200, 200);
contentPane=new JPanel();
contentPane.setBackground(Color.YELLOW);
contentPane.setLayout(new BorderLayout(0,0));
contentPane.setBorder(new EmptyBorder(5, 5, 5,5));
setContentPane(contentPane);
lblTip=new JLabel("JFabel 窗体获得焦点,灯亮了");
lblTip.setForeground(Color.cyan);
lblTip.setFont(new Font("微软雅黑",Font.PLAIN,14));
lblTip.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblTip,BorderLayout.NORTH);
lblTight=new JLabel();
lblTight.setHorizontalAlignment(SwingConstants.CENTER);
lblTight.setIcon(new ImageIcon(Windowfa.class.getResource("dengliang.png")));
contentPane.add(lblTight,BorderLayout.SOUTH);
addWindowFocusListener(new WindowFocusListener() {
public void windowLostFocus(WindowEvent e) {
lblTight.setIcon(new ImageIcon(Windowfa.class.getResource("dengmie.png")));
lblTip.setText("JFabel 窗体失去焦点,灯灭了");
}
public void windowGainedFocus(WindowEvent e) {
lblTight.setIcon(new ImageIcon(Windowfa.class.getResource("dengliang.png")));
lblTip.setText("JFabel 窗体获得焦点,灯亮了");
}
});
}
}
1、问题:WindowFocusListene中为什么需要run()方法,起什么作用。又为什么需要try....catch 语句。
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
Windowfa frame = new Windowfa();
frame.setVisible(true);
}catch(Exception e){
e.printStackTrace();
}
}
});
}
2、WindowFocusListene中 失去焦点后,需要由弹出窗口说明“程序暂停”等字样的窗体 老师求教。