Java GUI 点击按钮退出

时间:2024-03-11 15:57:15
import java.awt.*;
import java.awt.event.*;

public class TestFrameTwo implements ActionListener
{
    Frame f = new Frame("((((99999");
    
    public static void main(String[] args)
    {
        TestFrameTwo tf = new TestFrameTwo();
        tf.init();
    }
    
    public void init()
    {
        Button btn = new Button("退出");
        btn.addActionListener(this);
        f.add(btn);
        f.setSize(300,300);
        f.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent e)
    {
        f.setVisible(false);
        f.dispose();
        System.exit(0);
    }
}

 使用匿名对象版~

import java.awt.*;
import java.awt.event.*;

public class TestFrameThree {
    Frame f = new Frame("AAAA");
    public static void main(String[] args)
    {
        new TestFrameThree().init();
    }
    
    public void init()
    {
        Button btn = new Button("退出");
        btn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                f.setVisible(false);
                f.dispose();
                System.exit(0);
            }
        });
        f.add(btn);
        f.setSize(300,300);
        f.setVisible(true);
    }
}

确实简洁了很多。。Go Go Go ~