在Java Swing編程中,程序員還可以自定義對話框,一般可以從JDialog類來繼承。下面給出一個對話框類的代碼:
class HelpAbout extends JDialog implements ActionListener
{
JavaWord mainFrame;
JButton okButton;
javax.swing.Timer myTimer;
int Counter=0;
public HelpAbout(JavaWord mainFrame)
{
super(mainFrame,"關於本程序的說明",true); //true 代表為有模式對話框
this.mainFrame= mainFrame;
JPanel contentPanel=new JPanel();
contentPanel.setLayout(new BorderLayout());
JLabel imageLabel=new JLabel(new ImageIcon(".\images\javalogo.gif"));
contentPanel.add(imageLabel,BorderLayout.WEST);
JPanel authorInfoPane=new JPanel();
authorInfoPane.setLayout(new GridLayout(1,1));
JTextArea aboutContent=new JTextArea("本程序是作者在學習Java2 Swing編程的一個簡單的程序,\n並不作為商業目的使用。\n作者的聯系方式是:\n");
aboutContent.enable(false);
authorInfoPane.add(aboutContent);
contentPanel.add(authorInfoPane,BorderLayout.NORTH);
JPanel sysInfoPane=new JPanel();
sysInfoPane.setLayout(new GridLayout(5,1));
sysInfoPane.setBorder(BorderFactory.createLoweredBevelBorder());
contentPanel.add(sysInfoPane,BorderLayout.CENTER);
JLabel userName=new JLabel("本機的用戶名為:"+System.getProperty("user.name"));
JLabel osName=new JLabel("本機的操作系統是:"+System.getProperty("os.name"));
JLabel javaVersion=new JLabel("本機中所安裝的Java SDK的版本號是:"+System.getProperty("java.version"));
JLabel totalMemory=new JLabel("本機中Java虛擬機所可能使用的總內存數:"+Runtime.getRuntime().totalMemory()+"字節數" );
JLabel freeMemory=new JLabel("本機中Java虛擬機所剩余的內存數?quot;+Runtime.getRuntime().freeMemory()+"字節數" );
sysInfoPane.add(userName);
sysInfoPane.add(osName);
sysInfoPane.add(javaVersion);
sysInfoPane.add(totalMemory);
sysInfoPane.add(freeMemory);
JPanel OKPane=new JPanel();
okButton=new JButton("確定(O)",new ImageIcon(".\images\ok.gif"));
okButton.setMnemonic('O'); //設置快捷鍵為"Alt + O"
/*以下代碼是設置案鈕的Rollover圖象*/
Icon rollover = new ImageIcon(".\images\exit.gif");
Icon general = new ImageIcon(".\images\ok.gif");
Icon press = new ImageIcon(".\images\help.gif");
okButton.setRolloverEnabled(true);
okButton.setIcon(general); //設置離開時的圖象
okButton.setRolloverIcon(rollover); //設置在按紐上時的圖象
okButton.setPressedIcon(press); //設置在按下按紐時的圖象
this.getRootPane().setDefaultButton(okButton); //設置該按鈕為該對話框的默認的按鈕?.
okButton.addActionListener(this);
OKPane.add(okButton);
contentPanel.add("South",OKPane);
setContentPane(contentPanel);
// this.setResizable(false); //設置對話框為不可改變大小
myTimer=new javax.swing.Timer(1000,this);
myTimer.start();
}
public void actionPerformed(ActionEvent parm1)
{
// TODO: Add your code here
if(parm1.getSource()==okButton)
{
dispose();
}
else if(parm1.getSource()==myTimer)
{
Counter++;
this.setTitle("當前的定時器的值為:"+Counter+"秒");
}
}
}
在事件響應代碼中顯示出該對話框,其程序代碼如下:
HelpAbout aboutDialog=new HelpAbout(this);
aboutDialog.setSize(500,500);
aboutDialog.show();