AWT和Swing之间的基本区别:AWT 是基于本地方法的C/C++程序,其运行速度比较快;Swing是基于AWT 的Java程序,其运行速度比较慢。
对于一个嵌入式应用来说,目标平台的硬件资源往往非常有限,而应用程序的运行速度又是项目中至关重要的因素。
在这种矛盾的情况下,简单而高效的AWT 当然成了嵌入式Java的第一选择。
而在普通的基于PC或者是工作站的标准Java应用中,硬件资源对应用程序所造成的限制往往不是项目中的关键因素,所以在标准版的Java中则提倡使用Swing, 也就是通过牺牲速度来实现应用程序的功能。
1 1 package Com.MySwing; 2 2 import java.awt.GridBagConstraints; 3 3 import java.awt.GridBagLayout; 4 4 import java.awt.event.ActionEvent; 5 5 import java.awt.event.ActionListener; 6 6 import javax.swing.JButton; 7 7 import javax.swing.JFrame; 8 8 import javax.swing.JLabel; 9 9 import javax.swing.JPanel; 10 10 import javax.swing.JTextArea; 11 11 12 12 public class TwelveSwing { 13 13 14 14 public void go(){ 15 15 JFrame frame = new JFrame("login"); 16 16 frame.setSize(400,200);//设置窗体大小 17 17 frame.setVisible(true);//设置窗体可见 18 18 19 19 20 20 JPanel panel = new JPanel(); 21 21 panel.setLayout(new GridBagLayout()); 22 22 23 23 JLabel username = new JLabel("username"); 24 24 JLabel password = new JLabel("password"); 25 25 26 26 JTextArea username_input = new JTextArea("1"); 27 27 JTextArea password_input = new JTextArea("2"); 28 28 29 29 JButton ok = new JButton("OK"); 30 30 JButton cancel = new JButton("Cancel"); 31 31 JButton register = new JButton("Register"); 32 32 33 33 34 34 35 35 panel.add(username); 36 36 panel.add(password); 37 37 38 38 panel.add(username_input); 39 39 panel.add(password_input); 40 40 41 41 panel.add(ok); 42 42 panel.add(cancel); 43 43 panel.add(register); 44 44 frame.add(panel); 45 45 frame.setVisible(true); 46 46 47 47 48 48 GridBagConstraints c= new GridBagConstraints(); 49 49 50 50 c.gridx=1; 51 51 c.gridy=1; 52 52 c.weighty=4; 53 53 c.weightx=2; 54 54 panel.add(username,c); 55 55 56 56 c.gridx=2; 57 57 c.gridy=1; 58 58 c.gridwidth=1; 59 59 c.fill = GridBagConstraints.HORIZONTAL; 60 60 panel.add(username_input,c); 61 61 c.fill =GridBagConstraints.NONE; 62 62 63 63 c.gridx=1; 64 64 c.gridy=2; 65 65 c.gridwidth=1; 66 66 panel.add(password,c); 67 67 68 68 c.gridx =2; 69 69 c.gridy =2; 70 70 c.gridwidth =1; 71 71 c.fill = GridBagConstraints.HORIZONTAL; 72 72 panel.add(password_input,c); 73 73 c.fill =GridBagConstraints.NONE; 74 74 75 75 c.gridx=1; 76 76 c.gridy=8; 77 77 c.gridwidth=1; 78 78 panel.add(ok,c); 79 79 80 80 c.gridx=2; 81 81 c.gridy=8; 82 82 c.gridwidth=1; 83 83 panel.add(cancel,c); 84 84 85 85 c.gridx=3; 86 86 c.gridy=8; 87 87 c.gridwidth=1; 88 88 panel.add(register,c); 89 89 90 90 frame.setVisible(true); 91 91 ok.addActionListener(new ActionListener(){ 92 92 public void actionPerformed(ActionEvent e){ 93 93 } 94 94 }); 95 95 96 96 cancel.addActionListener(new ActionListener(){ 97 97 public void actionPerformed(ActionEvent e){ 98 98 } 99 99 }); 100100 101101 register.setEnabled(false); 102102 } 103103 104104 public static void main(String[] args ){ 105105 TwelveSwing tw=new TwelveSwing(); 106106 tw.go(); 107107 } 108108 }