import javax.swing.*;
import java.awt.event.*;
import java.awt.*;class WindowActionTest 
{
public static void main(String[] args) 
{
WindowFrame myFrame =new WindowFrame(); myFrame.show();
}
}class WindowFrame extends JFrame
{
public WindowFrame()
{
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); setTitle("My First Window"); ///////An window listener ,when the window closed ,another window will be showed
         //////An anonymous inner class
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
ShowDialogFrame dialogFrame =new ShowDialogFrame();

dialogFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); dialogFrame.show();
}
});
}
public static final int DEFAULT_WIDTH =300;
public static final int DEFAULT_HEIGHT =400;
};/////////////the frame of another window
class ShowDialogFrame extends JFrame
{
public ShowDialogFrame()
{
setTitle("Dialog"); Toolkit tool =Toolkit.getDefaultToolkit(); Dimension screenSize = tool.getScreenSize(); int screenWidth =screenSize.width; int screenHeight =screenSize.height; dialogX =screenWidth/2 -detaX;

dialogY =screenHeight/2 -detaY; setBounds(dialogX,dialogY,2*detaX,2*detaY); ShowDialog myDialog =new ShowDialog(); Container contentPane =getContentPane(); contentPane.add(myDialog); }
//////////the panel of another window ,a string has been draw in this panel
/////////a inner class
class ShowDialog extends JPanel
{

public void paintComponent(Graphics g)
{
super.paintComponent(g); g.drawString("Are you sure you want to close the window?",dialogX+positionX,dialogY+positionY); }
public static final int positionX =100;
public static final int positionY =100;



public static final int detaX =200;
public static final int detaY =200;
public int dialogX;
public int dialogY;

}
当关闭第一个窗口时,应该出来另外一个窗口,显示“Are you sure you want to close the window?”,关闭该窗口后程序正常退出。但运行上述代码只弹出了另一个窗口,关闭后也正常退出,但并未显示文字,不知道错在哪儿了

解决方案 »

  1.   

    class ShowDialog extends JPanel
    {

    public void paintComponent(Graphics g)
    {
    super.paintComponent(g); //g.drawString("Are you sure you want to close the window?",dialogX+positionX,dialogY+positionY); 
                               g.drawString("Are you sure you want to close the window?",positionX,positionY); //该坐标本来就是相对于自身的坐标,你加上自己位置的坐标,相对位置就超出窗口的大小了,所以显示的文字你就看不到了 }
    public static final int positionX =100;
    public static final int positionY =100;