在我們編寫JAVA代碼的過程中,需要給事件來源增加監聽事件,可是我們往往記不住這個事件來源有那些可以使用的事件,所以我參考《JAVA編程思想》,按照書上的說明,寫了如下的代碼,主要是能夠得到事件來源可以使用的事件的列表。
程式啟動並執行介面如下:
這個程式還是有點不完善,輸入的類名必須區分大小寫 ,另外程式是以javaapplet啟動並執行。
主要的代碼如下:
package niutool;
import niutool.Console;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*;
import java.util.regex.*;
public class ShowAddListeners extends JApplet {
private JTextField name = new JTextField(25);
private JTextArea results = new JTextArea(40, 65);
private static Pattern addListener =
Pattern.compile("(add/w+?Listener/(.*?/))");
private static Pattern qualifier =
Pattern.compile("/w+/.");
class NameL implements ActionListener {
public void actionPerformed(ActionEvent e) {
String nm = name.getText().trim();
if(nm.length() == 0) {
results.setText("沒有匹配");
return;
}
Class klass;
try {
klass = Class.forName("javax.swing." + nm);
} catch(ClassNotFoundException ex) {
results.setText("沒有匹配");
return;
}
Method[] methods = klass.getMethods();
results.setText("");
for(int i = 0; i < methods.length; i++) {
Matcher matcher =
addListener.matcher(methods[i].toString());
if(matcher.find())
results.append(qualifier.matcher(
matcher.group(1)).replaceAll("") + " ");
}
}
}
public void init() {
NameL nameListener = new NameL();
name.addActionListener(nameListener);
JPanel top = new JPanel();
top.add(new JLabel("Swing 類名 (press ENTER):"));
top.add(name);
Container cp = getContentPane();
cp.add(BorderLayout.NORTH, top);
cp.add(new JScrollPane(results));
// Initial data and test:
name.setText("JTextArea");
nameListener.actionPerformed(
new ActionEvent("", 0 ,""));
}
public static void main(String[] args) {
Console.run(new ShowAddListeners(), 500,400);
}
} ///:~
裡面import niutool.Console,引入了一個Console的工具,原始碼如下:
package niutool;
import javax.swing.*;
import java.awt.event.*;
public class Console {
// Create a title string from the class name:
public static String title(Object o) {
String t = o.getClass().toString();
// Remove the word "class":
if(t.indexOf("class") != -1)
t = t.substring(6);
return t;
}
public static void
run(JFrame frame, int width, int height) {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width, height);
frame.setVisible(true);
}
public static void
run(JApplet applet, int width, int height) {
JFrame frame = new JFrame(title(applet));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(width, height);
applet.init();
applet.start();
frame.setVisible(true);
}
public static void
run(JPanel panel, int width, int height) {
JFrame frame = new JFrame(title(panel));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(panel);
frame.setSize(width, height);
frame.setVisible(true);
}
} ///:~
還有不明白的地方,你可以看看《JAVA編程思想》