java中窗口事件代码 java 窗口( 三 )


修改代码如下
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing--窗体正在关闭事件");
//f.setVisible(false);//隐藏窗口
f.dispose();//销毁窗口--这行代码会触发windowClosed事件
}
还有其他一些细节的修改,参考下面的代码
import java.awt.*;
import java.awt.event.*;
//类名不要写一个小写字母,推荐写一个完整的名词来作为类名
public class EventDemo {
public static void main(String[] args) {
Frame f = new Frame("hello");
f.setSize(300, 300);
f.setLocation(300, 200);
//f.setVisible(true);//不要先显示窗口, 先显示了窗口,就看不到"窗口打开事件"了
f.addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) {
System.out.println("windowOpened--窗体打开事件");
}
@Override
public void windowIconified(WindowEvent e) {
System.out.println("windowIconified--窗体图标化事件");
}
@Override
public void windowDeiconified(WindowEvent e) {
System.out.println("windowDeiconifie--窗体取消图标化事件");
}
@Override
public void windowDeactivated(WindowEvent e) {
System.out.println("windowDeactivated--窗体停用事件");
}
@Override
public void windowClosing(WindowEvent e) {
System.out.println("windowClosing--窗体正在关闭事件");
//f.setVisible(false);//隐藏窗口
f.dispose();//销毁窗口
}
@Override
public void windowClosed(WindowEvent e) {
System.out.println("windowClosed--窗体关闭事件");
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e) {
System.out.println("windowActivated--窗体激活事件");
}
});
f.setVisible(true);//窗口显示
}
}
Java 窗体事件import java.awt.event.*;
import javax.swing.*;
public class WindowEvent extends JFrame{
public static void main(){
WindowEvent frame = new WindowEvent();
frame.setVisible(true);
}
public WindowEvent(){
super();
addWindowFocusListener( new MYWindowFocusListener());
setTitle("WindowEvent");
setBounds(100,100,500,375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private class MYWindowFocusListener implements WindowFocusListener{
public void windowGainedFocus(java.awt.event.WindowEvent e) {
}
public void windowLostFocus(java.awt.event.WindowEvent e) {
}
}
}
private class MYWindowFocusListener() implements WindowFocusListener{
MYWindowFocusListener是个内部类 后面不能加()它是类不是方法,应该是
private class MYWindowFocusListener implements WindowFocusListener{
这段java 代码怎么添加动作响应事件,使点击它可以弹出一个窗口,窗口中有一句话你少了一个菜单项,在菜单项上添加监听器 。
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class TestWin extends JFrame {
{
JMenuBar jmb = new JMenuBar();//创建菜单栏
JMenu jm1 = new JMenu("帮助");//创建菜单
jmb.add(jm1);
JMenuItem jmi = new JMenuItem("帮助");//创建菜单项
jm1.add(jmi);//把菜单项添加到菜单中
jmi.addActionListener(new ActionListener() {//给菜单项添加动作监听器
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(TestWin.this, "窗口中有一句话");//显示消息对话框
}
});
setJMenuBar(jmb);
setTitle("时钟");// 标题

推荐阅读