package com.swing.demo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; /*** * 对话框测试 * * @author Dawning * */ public class DialogTest { public static void main(String[] agar){ EventQueue.invokeLater(new Runnable(){ public void run(){ DialogFrame frame = new DialogFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class DialogFrame extends JFrame{ public DialogFrame(){ //set JFrame title the DialogTest setTitle("DialogTest"); //set JFrame size 300 and 200 setSize(300,200); //set JFrame location x=150 and y=150 setLocation(150,150); //create JMenuBar JMenuBar menuBar = new JMenuBar(); menuBar.setBackground(Color.GRAY); setJMenuBar(menuBar); //create Jmenu 【file】 JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); //create JMenuItem 【About,Exit】 //add ActionListener show owner JFrame //Ok Button and ActionListtener new JFrame visible the false JMenuItem aboutItem = new JMenuItem("About"); aboutItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { if(dialog == null) dialog = new AboutDialog(DialogFrame.this); dialog.setVisible(true); } }); fileMenu.add(aboutItem); JMenuItem exitItem = new JMenuItem("Exit"); exitItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { System.exit(0); } }); fileMenu.add(exitItem); } private AboutDialog dialog; } class AboutDialog extends JDialog{ public AboutDialog(JFrame owner){ super(owner,"About DialogTest",true); //add Html label to center add( new JLabel("<html><h1><i>Core Java</i></h1/><hr>By Cay Horstmann and Gary Cornell</html>"), BorderLayout.CENTER); //ok button closes the dialog JButton ok = new JButton("ok"); ok.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { setVisible(false); }}); JPanel panel = new JPanel(); panel.add(ok); add(panel,BorderLayout.SOUTH); setSize(250,150); setLocation(150,150); } }