import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TestGUI
{
public static void main(String[] args)
{
frame f = new frame();
//还可以在这里加上一句
①f.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
f.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
int i;
i=JOptionPane.showConfirmDialog(null,"are you ok");
if(i==JOptionPane.YES_OPTION)
{
System.exit(0););//或者还可以写成
this.dispose();//这两句都可以实现关闭窗口
}
else
{
}
}
});
}
}
class panel extends JPanel
{
public panel()
{
makeButton("red",Color.RED);
makeButton("yellow",Color.yellow);
}
private void makeButton(String name,final Color c)
{
Button button=new Button(name);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
setBackground(c);
}
}
);
add(button);
}
}
class frame extends JFrame
{
public frame()
{
setTitle("test");
setSize(300,200);
panel p= new panel();
add(p);
}
}
--------------------next---------------------