注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

千鸟

本blog所有日志均系原创 转载请注明出处

 
 
 

日志

 
 

Swing Application Framework 初探1  

2007-08-03 18:10:47|  分类: J2SE |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

Swing Application Framework (JSR 296)是 swing程序的框架,在netbeans有附带的

要添加这个库,在netbeans添加libSwing Application Framework

这篇文章是我选取翻译的,废话一律省略,主要看代码,原文在这里: http://java.sun.com/developer/technicalArticles/javase/swingappfr/#actions

Code Example 1

 
public class BasicApp implements Runnable {        JFrame mainFrame;      JLabel label;        public void run() {          mainFrame = new JFrame("BasicApp");          label = new JLabel("Hello, world!");          label.setFont(new Font("SansSerif", Font.PLAIN, 22));          mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);          mainFrame.addWindowListener(new WindowAdapter() {              public void windowClosing(WindowEvent e) {                  mainFrame.setVisible(false);                  // Perform any other operations you might need                  // before exit.                  System.exit(0);              }          });          mainFrame.add(label);          mainFrame.pack();          mainFrame.setVisible(true);      }        public static void main(String[] args) {          Runnable app = new BasicApp();          try {              SwingUtilities.invokeAndWait(app);          } catch (InvocationTargetException ex) {              ex.printStackTrace();          } catch (InterruptedException ex) {              ex.printStackTrace();          }      }  }  

SwingUtilities.invokeAndWait(Runnable) 是swing推荐的程序初始化的方法.
把实现了Runnable接口的的gui,用另一个线程调用执行.
这个有了这个思想,就好使用框架了.

 

Code Example 2

 
public class BasicFrameworkApp extends Application {      private JFrame mainFrame;      private JLabel label;        @Override      protected void startup() {          mainFrame = new JFrame("BasicFrameworkApp");          mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);          mainFrame.addWindowListener(new WindowAdapter() {              public void windowClosing(WindowEvent e) {                  mainframe.setVisible(false);                  exit();              }          });          label = new JLabel("Hello, world!");          mainFrame.add(label);          mainFrame.pack();          mainFrame.setVisible(true);      }        public static void main(String[] args) {          Application.launch(BasicFrameworkApp.class, args);      }  }  

对比一下和上个例子的发现很像是吧,
Application.launch();载入一个线程,然后执行它的run();run方法又调用startup()
代码还是很长是吧,还要自己处理窗口关闭事件.下面的代码就简单多了,按默认的方法处理窗口关闭.

Code Example 3

 
public class BasicSingleFrameApp extends SingleFrameApplication {      JLabel label;        @Override      protected void startup() {          getMainFrame().setTitle("BasicSingleFrameApp");          label = new JLabel("Hello, world!");          label.setFont(new Font("SansSerif", Font.PLAIN, 22));          show(label);      }        public static void main(String[] args) {          Application.launch(BasicSingleFrameApp.class, args);      }    }  

 

 

SingleFrameApplication 是个实现了Runnable接口的Frame
要把组件添加就去用show();
show(label); 

Code Example 4

 
@Override  protected void shutdown() {      // The default shutdown saves session window state.      super.shutdown();      // Now perform any other shutdown tasks you need.  }  

protected void shutdown()
调用System.exit()退出虚拟机

Code Example 5

 
public class ConfirmExit extends SingleFrameApplication {      private JButton exitButton;        @Override      protected void startup() {          getMainFrame().setTitle("ConfirmExit");          exitButton = new JButton("Exit Application");          exitButton.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent e) {                  exit(e);              }            });          addExitListener(new ExitListener() {              public boolean canExit(EventObject e) {                  boolean bOkToExit = false;                  Component source = (Component) e.getSource();                  bOkToExit = JOptionPane.showConfirmDialog(source,                                  "Do you really want to exit?") ==                                  JOptionPane.YES_OPTION;                  return bOkToExit;              }              public void willExit(EventObject event) {                }          });          show(exitButton);      }        @Override      protected void shutdown() {          // The default shutdown saves session window state.          super.shutdown();          // Now perform any other shutdown tasks you need.          // ...      }        /**       * @param args the command-line arguments       */      public static void main(String[] args) {          Application.launch(ConfirmExit.class, args);      }    }  

ExitListener接口
public boolean canExit(EventObject e)   返回true,则自动调用下面的willExit(),接着调用shutdown()
public void willExit(EventObject e)

 

Code Example 6

 
public class ConfirmExit extends SingleFrameApplication {      private JButton exitButton;        @Override      protected void startup() {          getMainFrame().setTitle("ConfirmExit");          exitButton = new JButton("Exit Application");          exitButton.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent e) {                  exit(e);              }            });          addExitListener(new ExitListener() {              public boolean canExit(EventObject e) {                  boolean bOkToExit = false;                  Component source = (Component) e.getSource();                  bOkToExit = JOptionPane.showConfirmDialog(source,                                  "Do you really want to exit?") ==                                  JOptionPane.YES_OPTION;                  return bOkToExit;              }              public void willExit(EventObject event) {                }          });          show(exitButton);      }        @Override      protected void shutdown() {          // The default shutdown saves session window state.          super.shutdown();          // Now perform any other shutdown tasks you need.          // ...      }        /**       * @param args the command-line arguments       */      public static void main(String[] args) {          Application.launch(ConfirmExit.class, args);      }    }  

数据绑定
HelloWorld 的数据放在程序外面,
还resource对象 返回多 ImageIcon Icon 等多种数据,又节约了不少代码.特神奇的地方放在下面个例子,可以在配置文件里,写程序

Code Example 7

 
helloLabel = Hello, world!  color = #AABBCC  title = HelloWorld with Resources  

先做好resources/HelloWorld.properties
也可以写成 resources/HelloWorld_zh_CN.properties,如果是中国的用户会自动选取这个文件
但是把汉字直接写在配置文件了,在这个框架下读出来还是一团乱码.  sun推荐用\? 这种形式的unicode码来表示外国字符.

Code Example 8

 
btnShowTime.text = Show current time!  btnShowTime.icon = refresh.png    txtShowTime.text = Press the button to retrieve time.  txtShowTime.editable = false  

 

Code Example 9

 
public class ShowTimeApp extends SingleFrameApplication {      JPanel timePanel;      JButton btnShowTime;      JTextField txtShowTime;        @Override      protected void startup() {          timePanel = new JPanel();          btnShowTime = new JButton();          txtShowTime = new JTextField();            // Set UI component names so that the          // framework can inject resources automatically into          // these components. Resources come from similarly          // named keys in resources/ShowTimeApp.properties.          btnShowTime.setName("btnShowTime");          txtShowTime.setName("txtShowTime");            btnShowTime.addActionListener(new ActionListener() {              public void actionPerformed(ActionEvent e) {                  Date now = new Date();                  txtShowTime.setText(now.toString());              }          });            timePanel.add(btnShowTime);          timePanel.add(txtShowTime);          show(timePanel);      }      // ...  }  

对按钮设定了名字(btnShowTime.setName("btnShowTime"))后,

Code Example 10

 
public class NameEntryPanel extends javax.swing.JPanel {        @Resource      String greetingMsg;        ApplicationContext ctx;      ResourceMap resource;        /** Creates new form NameEntryPanel. */      public NameEntryPanel(ApplicationContext ctxt) {          initComponents();          ResourceMap resource = ctxt.getResourceMap(NameEntryPanel.class);          resource.injectFields(this);      }        private void initComponents() {          lblNamePrompt = new javax.swing.JLabel();          txtName = new javax.swing.JTextField();          btnGreet = new javax.swing.JButton();            lblNamePrompt.setName("lblNamePrompt");          btnGreet.setName("btnGreet");          // ...      }        private void btnGreetActionPerformed(java.awt.event.ActionEvent evt) {          String personalMsg = String.format(greetingMsg, txtName.getText());          JOptionPane.showMessageDialog(this, personalMsg);      }        private javax.swing.JButton btnGreet;      private javax.swing.JLabel lblNamePrompt;      private javax.swing.JTextField txtName;  }  

Code Example 11

 
# resources/NameEntryPanel.properties  NameEntryPanel.greetingMsg = Hello, %s, this string was injected!  

Code Example 12

 
# resources/ConverterApp.properties  Application.id = ConverterApp  Application.title = ResourceConverter Demo    msg = This app demos ResourceConverter.  font = Arial-BOLD-22  color = #BB0000  icon = next.png    **  public class ConverterApp extends SingleFrameApplication {      protected void startup() {          ApplicationContext ctx = getContext();          ResourceMap resource = ctx.getResourceMap();            String msg;          Color color;          Font font;          Icon icon;          JLabel label;            // Use resource converters to convert text representations          // of resources into Color and Font objects.          msg = resource.getString("msg");          color = resource.getColor("color");          font = resource.getFont("font");          icon = resource.getIcon("icon");            label = new JLabel(msg);          label.setOpaque(false);          label.setForeground(color);          label.setFont(font);          label.setIcon(icon);            show(label);      }      // ...  }  

Code Example 13

 
private void btnGreetActionPerformed(java.awt.event.ActionEvent evt) {      String personalMsg = resource.getString("NameEntryPanel.greetingMsg", txtName.getText());      JOptionPane.showMessageDialog(this, personalMsg);  }  

Code

  评论这张
 
阅读(1232)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017