public class SomeGUI extends JFrame { ... button member declarations ...
protected void buildGUI() { button1 = new JButton(); button2 = new JButton(); ...
button1.addActionListener( new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { // do something } } ); …repeat for each button
如果應(yīng)用一般內(nèi)部類,程序就會(huì)像這樣:
public class SomeGUI extends JFrame { ... button member declarations
// inner class definitions class Button1Handler implements ActionListener { public void actionPerformed(ActionEvent e) { // do something } } ... define an inner member class for each button
protected void buildGUI() { // initialize the buttons button1 = new JButton(); button2 = new JButton(); ...
// register an inner class action listener instance // for each button button1.addActionListener(new Button1Handler()); .. repeat for each button
沒有東西是十全十美的,一樣?xùn)|西有它的長(zhǎng)處必然會(huì)有它的短處。內(nèi)部類也有它們不足的地方。從維護(hù)的角度來說,一個(gè)不熟練的開發(fā)人員就會(huì)覺得內(nèi)部類難以理解。應(yīng)用內(nèi)部類會(huì)使增加你的類的代碼總行數(shù)。此外,從開發(fā)的角度來說,大部分的Java工具都在對(duì)內(nèi)部類的支持上都存在或多或少不足的地方。For example, I use IBM's VisualAge for Java for my day-to-day coding. While inner classes will compile within VisualAge, there is no inner class browser or template. Instead, you must simply type the inner class directly into the class definition. That unfortunately makes browsing the inner class difficult. It is also difficult to type since you lose many of VisualAge's code completion aids when you type into the class definition or use an inner class.
For example, I use IBM's VisualAge for Java for my day-to-day coding. While inner classes will compile within VisualAge, there is no inner class browser or template. Instead, you must simply type the inner class directly into the class definition. That unfortunately makes browsing the inner class difficult. It is also difficult to type since you lose many of VisualAge's code completion aids when you type into the class definition or use an inner class. 原文鏈接: