SwingConsole

       Java的Swing默认不是线程安全的,类的调度应该由线程分派器来安排。如果每个类都各个各的调度,有可能造成线程紊乱,带来一些难以检测的错误。

       对于编写实验性代码(每次都只有一个JFrame),如果每次都要编写重复的main函数,显然太浪费精力。利用Java的反射机制,可以编写一个通用的“Swing控制台”用作调度其他类。另外,将代码做一些简单的修改就可以应用于具体应用。

 1 import java.util.*;
 2 import java.lang.reflect.*;
 3 import javax.swing.*;
 4 import java.awt.*;
 5 
 6 class SwingConsole {
 7 
 8     public static void main(String[] args) {
 9         String className;
10         //get class name
11         if(args.length > 0){
12             className = args[0];
13         }
14         else{
15             System.out.println("Enter JFrame class name (e.g java.util.Date): ");
16             Scanner in = new Scanner(System.in);
17             className = in.next();
18         }
19 
20         try{
21             //get class
22             final Class cl = Class.forName(className);
23             if(cl.getSuperclass() != JFrame.class){
24                 //is not a JFrame
25                 System.out.println("It is not a JFrame class"); 
26                 return;
27             }
28             else{
29                 //get class constructor
30                 final Constructor constructor = cl.getConstructor();
31             
32                 //run JFrame
33                 EventQueue.invokeLater(new Runnable(){
34                     public void run(){
35                         try{
36                             JFrame frame = (JFrame) constructor.newInstance();
37                             frame.setTitle(frame.getClass().getName());
38                             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
39                             frame.setVisible(true);
40                         }
41                         catch(Exception e){
42                             e.printStackTrace();
43                         }
44                     }
45                 });
46             }
47         }
48         catch(Exception e){
49             e.printStackTrace();
50         }
51     }
52 }
原文地址:https://www.cnblogs.com/7hat/p/3724730.html