Swing的程序设计经验总结与清晰设计模型(2012.06.12)

直接进入主题,最近项目需要Swing的知识,自我总结了一些经验供大家分享: 

 

Swing的程序设计一般可按照下列流程进行:
  1. 引入Swing包
  2. 选择"外观和感觉"
  3. 设置顶层容器
  4. 设置按钮和标签
  5. 向容器中添加组件
  6. 在组件周围添加边界
  7. 进行事件处理

 

对于以上的开发流程,相对于重要的有几种常见的布局和事件的处理,以下对这两个重要的知识进行详细的分析。

 

1、首先分别介绍几种最常用的布局管理器:FlowLayout、BorderLayout、BoxLayout、CardLayout、GridLayout和GridBagLayout。

 

代码演示(出自博友http://zhangjunhd.blog.51cto.com/113473/128174

FlowLayout

FlowLayout类是最简单的布局管理器。它按照和页面上排列单词的类似方式来安排组件----从左到右,直至没有多余的空间,然后转到下一行。

效果:

 

内容面板代码:

Java代码

  1. public static     void addComponentsToPane(Container pane) {
  2. pane.setLayout(new     FlowLayout());
  3. pane.add(new     JButton("Button 1"));
  4. pane.add(new     JButton("Button 2"));
  5. pane.add(new     JButton("Button 3"));
  6. pane.add(new     JButton("Long-Named Button 4"));
  7. pane.add(new     JButton("5"));
  8. }

public static voidaddComponentsToPane(Container pane) {

    pane.setLayout(new FlowLayout());

    pane.add(new JButton("Button1"));

    pane.add(new JButton("Button2"));

    pane.add(new JButton("Button3"));

    pane.add(new JButton("Long-NamedButton 4"));

    pane.add(new JButton("5"));

}

BorderLayout

一个BorderLayout对象将界面分成五大区域,分别用BorderLayout类的静态常量指定:

-PAGE_START

-PAGE_END

-LINE_START

-LINE_END

-CENTER

效果:

内容面板代码:

Java代码

  1. public static     void addComponentsToPane(Container pane) {
  2. JButton     button = new JButton("Button 1 (PAGE_START)");
  3. pane.add(button,     BorderLayout.PAGE_START);
  4. button = new     JButton("Button 2 (CENTER)");
  5. button.setPreferredSize(new     Dimension(200, 100));
  6. pane.add(button,     BorderLayout.CENTER);
  7. button = new     JButton("Button 3 (LINE_START)");
  8. pane.add(button,     BorderLayout.LINE_START);
  9. button = new     JButton("Long-Named Button 4 (PAGE_END)");
  10. pane.add(button,     BorderLayout.PAGE_END);
  11. button = new     JButton("5 (LINE_END)");
  12. pane.add(button,     BorderLayout.LINE_END);
  13. }

public static void addComponentsToPane(Containerpane) {      

    JButton button = new JButton("Button 1(PAGE_START)");

    pane.add(button,BorderLayout.PAGE_START);     

    button = new JButton("Button 2(CENTER)");

    button.setPreferredSize(new Dimension(200,100));

    pane.add(button, BorderLayout.CENTER);   

    button = new JButton("Button 3(LINE_START)");

    pane.add(button,BorderLayout.LINE_START);     

    button = new JButton("Long-NamedButton 4 (PAGE_END)");

    pane.add(button,BorderLayout.PAGE_END);      

    button = new JButton("5(LINE_END)");

    pane.add(button, BorderLayout.LINE_END);

}

BoxLayout

BoxLayout可以将组件由上至下或由左至右依次加入当前面板。

效果:

内容面板代码:

Java代码

  1. public static     void addComponentsToPane(Container pane) {
  2. JPanel xPanel     = new JPanel();
  3. xPanel.setLayout(new     BoxLayout(xPanel, BoxLayout.X_AXIS));
  4. addButtons(xPanel);    
  5. JPanel yPanel     = new JPanel();
  6. yPanel.setLayout(new     BoxLayout(yPanel, BoxLayout.Y_AXIS));
  7. addButtons(yPanel);    
  8.  
  9. pane.add(yPanel,     BorderLayout.PAGE_START);
  10. pane.add(xPanel,     BorderLayout.PAGE_END);
  11. }
  12.  
  13. private     static void addAButton(String text, Container container) {
  14. JButton     button = new JButton(text);
  15. button.setAlignmentX(Component.CENTER_ALIGNMENT);    
  16. container.add(button);    
  17. }
  18.  
  19. private static     void addButtons(Container container) {
  20. addAButton("Button     1", container);
  21. addAButton("Button     2", container);
  22. addAButton("Button     3", container);
  23. addAButton("Long-Named     Button 4", container);
  24. addAButton("5",     container);
  25. }

public static void addComponentsToPane(Containerpane) {

    JPanel xPanel = new JPanel();

    xPanel.setLayout(new BoxLayout(xPanel,BoxLayout.X_AXIS));

    addButtons(xPanel);

    JPanel yPanel = new JPanel();

    yPanel.setLayout(new BoxLayout(yPanel,BoxLayout.Y_AXIS));

    addButtons(yPanel);

   

    pane.add(yPanel, BorderLayout.PAGE_START);

    pane.add(xPanel, BorderLayout.PAGE_END);

}

 

private static voidaddAButton(String text, Container container) {

    JButton button = new JButton(text);

    button.setAlignmentX(Component.CENTER_ALIGNMENT);

    container.add(button);

}

 

private static voidaddButtons(Container container) {

    addAButton("Button 1",container);

    addAButton("Button 2",container);

    addAButton("Button 3",container);

    addAButton("Long-Named Button 4",container);

    addAButton("5", container);

}

CardLayout

卡片布局和其他布局不同,因为它隐藏了一些组件。卡片布局就是一组容器或者组件,它们一次仅仅显是一个,组中的每个容器称为卡片。

效果:

内容面板代码:

Java代码

  1. public void     addComponentToPane(Container pane) {
  2. final JPanel     contentPanel = new JPanel();
  3. JPanel     controlPanel = new JPanel();
  4. final     CardLayout cardLayout=new CardLayout();;
  5. pane.setLayout(new     BorderLayout());
  6. pane.add(contentPanel,     BorderLayout.CENTER);
  7. pane.add(controlPanel,     BorderLayout.PAGE_END);
  8. controlPanel.setLayout(new     FlowLayout());
  9.  
  10. JButton[] b =     new JButton[10];
  11. for (int i =     0; i < 10; i++) {
  12. b[i] = new     JButton("No." + i);
  13. contentPanel.add(b[i]);    
  14. }
  15. contentPanel.setLayout(cardLayout);    
  16. JButton     nextButton = new JButton("next");
  17. nextButton.addActionListener(new     ActionListener(){
  18. public void     actionPerformed(ActionEvent e) {
  19. cardLayout.next(contentPanel);    
  20. }});
  21. controlPanel.add(nextButton);    
  22. }

public voidaddComponentToPane(Container pane) {

    final JPanel contentPanel = new JPanel();

    JPanel controlPanel = new JPanel();

    final CardLayout cardLayout=newCardLayout();;

    pane.setLayout(new BorderLayout());

    pane.add(contentPanel,BorderLayout.CENTER);

    pane.add(controlPanel,BorderLayout.PAGE_END);

    controlPanel.setLayout(new FlowLayout());

 

    JButton[] b = new JButton[10];

    for (int i = 0; i < 10; i++) {

       b[i] = new JButton("No." + i);

       contentPanel.add(b[i]);

    }

    contentPanel.setLayout(cardLayout);

    JButton nextButton = newJButton("next");

    nextButton.addActionListener(newActionListener(){

       public void actionPerformed(ActionEvente) {

           cardLayout.next(contentPanel);

       }});

    controlPanel.add(nextButton);

}

GridLayout

GridLayout让你建立一个组件表格,并且当组件加入时,会依序又左至右,由上至下填充到每个格子,它不能由你指定想放那个格子就放那个格子

效果:

内容面板代码:

Java代码

  1. public static     void addComponentsToPane(Container pane) {
  2. JButton[]     buttons = new JButton[9];

pane.setLayout(newGridLayout(3, 3));

  1. for (int i =     0; i < buttons.length; i++) {
  2. buttons[i] =     new JButton(i + "");
  3. pane.add(buttons[i]);    
  4. }
  5. }

public static voidaddComponentsToPane(Container pane) {

    JButton[] buttons = new JButton[9];

    pane.setLayout(new GridLayout(3, 3));

    for (int i = 0; i < buttons.length; i++){

       buttons[i] = new JButton(i +"");

       pane.add(buttons[i]);

    }

}

GridBagLayout

GridBagLayout是所有AWT布局管理器当中最复杂的,同时他的功能也是最强大的。GridBagLayout同GridLayout一样,在容器中以网格形式来管理组件。但GridBagLayout功能要来得强大得多。

1、GridBagLayout管理的所有行和列都可以是大小不同的;

2、GridLayout把每个组件限制到一个单元格,而GridBagLayout并不这样:组件在容器中可以占据任意大小的矩形区域。

GridBagLayout通常由一个专用类来对他布局行为进行约束,该类叫GridBagConstraints。其中有11个公有成员变量,GridBagConstraints可以从这11个方面来进行控制和操纵。这些内容是:

1、gridx—组件的横向坐标;

2、girdy—组件的纵向坐标;

3、gridwidth—组件的横向宽度,也就是指组件占用的列数;

4、gridheight—组件的纵向长度,也就是指组件占用的行数;

5、weightx—指行的权重,告诉布局管理器如何分配额外的水平空间;

6、weighty—指列的权重,告诉布局管理器如何分配额外的垂直空间;

7、anchor—当组件小于其显示区域时使用此字段;

8、fill—如果显示区域比组件的区域大的时候,可以用来控制组件的行为。控制组件是垂直填充,还是水平填充,或者两个方向一起填充;

9、insets—指组件与表格空间四周边缘的空白区域的大小;

10、ipadx— 组件间的横向间距,组件的宽度就是这个组件的最小宽度加上ipadx值;

11、ipady— 组件间的纵向间距,组件的高度就是这个组件的最小高度加上ipady值。

说明:

1、gridx,gridy:其实就是组件行列的设置,注意都是从0开始的,比如 gridx=0,gridy=1时放在0行1列;

2、gridwidth,gridheight:默认值为1;GridBagConstraints.REMAINDER常量,代表此组件为此行或此列的最后一个组件,会占据所有剩余的空间;

3、weightx,weighty:当窗口变大时,设置各组件跟着变大的比例。比如组件A的weightx=0.5,组件B的weightx=1,那么窗口X轴变大时剩余的空间就会以1:2的比例分配给组件A和B;

4、anchor:当组件空间大于组件本身时,要将组件置于何处。有CENTER(默认值)、NORTH、NORTHEAST、EAST、SOUTHEAST、WEST、NORTHWEST选择。

5、insets:设置组件之间彼此的间距。它有四个参数,分别是上,左,下,右,默认为(0,0,0,0)。

效果:

 

内容面板代码:

Java代码

  1. public static     void addComponentsToPane(Container pane) {
  2. JButton     button;
  3. pane.setLayout(new     GridBagLayout());
  4. GridBagConstraints     c = new GridBagConstraints();
  5.  
  6. button = new     JButton("Button 1");
  7. c.fill =     GridBagConstraints.HORIZONTAL;
  8. c.gridx = 0;
  9. c.gridy = 0;
  10. pane.add(button,     c);
  11.  
  12. button = new     JButton("Button 2");
  13. c.fill =     GridBagConstraints.HORIZONTAL;
  14. c.weightx =     0.5;
  15. c.gridx = 1;
  16. c.gridy = 0;
  17. pane.add(button,     c);
  18.  
  19. button = new     JButton("Button 3");
  20. c.fill =     GridBagConstraints.HORIZONTAL;
  21. c.weightx =     0.5;
  22. c.gridx = 2;
  23. c.gridy = 0;
  24. pane.add(button,     c);
  25.  
  26. button = new     JButton("Long-Named Button 4");
  27. c.fill =     GridBagConstraints.HORIZONTAL;
  28. c.ipady = 40;     // make this component tall
  29. c.weightx =     0.0;
  30. c.gridwidth =     3;
  31. c.gridx = 0;
  32. c.gridy = 1;
  33. pane.add(button,     c);
  34.  
  35. button = new     JButton("5");
  36. c.fill =     GridBagConstraints.HORIZONTAL;
  37. c.ipady = 0;     // reset to default
  38. c.weighty =     1.0; // request any extra vertical space
  39. c.anchor =     GridBagConstraints.PAGE_END; // bottom of space
  40. c.insets =     new Insets(10, 0, 0, 0); // top padding
  41. c.gridx = 1;     // aligned with button 2
  42. c.gridwidth =     2; // 2 columns wide
  43. c.gridy = 2;     // third row
  44. pane.add(button,     c);
  45. }

public static voidaddComponentsToPane(Container pane) {

    JButton button;

    pane.setLayout(new GridBagLayout());

    GridBagConstraints c = newGridBagConstraints();

 

    button = new JButton("Button 1");

    c.fill = GridBagConstraints.HORIZONTAL;

    c.gridx = 0;

    c.gridy = 0;

    pane.add(button, c);

 

    button = new JButton("Button 2");

    c.fill = GridBagConstraints.HORIZONTAL;

    c.weightx = 0.5;

    c.gridx = 1;

    c.gridy = 0;

    pane.add(button, c);

 

    button = new JButton("Button 3");

    c.fill = GridBagConstraints.HORIZONTAL;

    c.weightx = 0.5;

    c.gridx = 2;

    c.gridy = 0;

    pane.add(button, c);

 

    button = new JButton("Long-NamedButton 4");

    c.fill = GridBagConstraints.HORIZONTAL;

    c.ipady = 40; // make this component tall

    c.weightx = 0.0;

    c.gridwidth = 3;

    c.gridx = 0;

    c.gridy = 1;

    pane.add(button, c);

 

    button = new JButton("5");

    c.fill = GridBagConstraints.HORIZONTAL;

    c.ipady = 0; // reset to default

    c.weighty = 1.0; // request any extravertical space

    c.anchor = GridBagConstraints.PAGE_END; //bottom of space

    c.insets = new Insets(10, 0, 0, 0); // toppadding

    c.gridx = 1; // aligned with button 2

    c.gridwidth = 2; // 2 columns wide

    c.gridy = 2; // third row

    pane.add(button, c);

    }

一个GardBagLayout布局的左右选择框,代码GridBagLayoutFrame.java见附件,效果:

2、事件监听(事件监听的三种方式)

直接贴代码(该代码来源于网络博友)

/*

    *Simple1.java - 处理事件的第一种方法

    *在这个例子中,利用一个ActionListener来监听事件源产生的事件

    *用一些if语句来决定是哪个事件源

   */

   import java.awt.*;

   import java.awt.event.*;

   import javax.swing.*;

    publicclass Simple1

    {

   private static JFrame frame; // 定义为静态变量以便main使用

   private static JPanel myPanel; // 该面板用来放置按钮组件

   private JButton button1;    // 这里定义按钮组件

   private JButton button2;    // 以便让ActionListener使用

   public Simple1()             // 构造器, 建立图形界面

    {

          // 新建面板

          myPanel = new JPanel();

          // 新建按钮

          button1 = new JButton("按钮1");   // 新建按钮1

          button2 = new JButton("按钮2");

          SimpleListener ourListener = new SimpleListener();

   // 建立一个actionlistener让两个按钮共享

          button1.addActionListener(ourListener);

          button2.addActionListener(ourListener);

          myPanel.add(button1); // 添加按钮到面板

          myPanel.add(button2);

    }

   private class SimpleListener implements ActionListener

    {

   /*

       * 利用该内部类来监听所有事件源产生的事件

       * 便于处理事件代码模块化

       */

          public void actionPerformed(ActionEvent e)

          {

            // 利用getActionCommand获得按钮名称

            // 也可以利用getSource()来实现

            // if (e.getSource() ==button1)

            String buttonName = e.getActionCommand();

            if (buttonName.equals("按钮1")

               JOptionPane.showMessageDialog(frame,

                                               "按钮1 被点击";

            else if (buttonName.equals("按钮2")

               JOptionPane.showMessageDialog(frame,

                                              "按钮2 被点击");

            else

               JOptionPane.showMessageDialog(frame,

                                              "Unknown event" );

          }

    }

   public static void main(String s[])

    {

          Simple1 gui = new Simple1(); // 新建Simple1组件

          frame = new JFrame("Simple1");   // 新建JFrame

          // 处理关闭事件的通常方法

          frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e)

                 {System.exit(0);} });

          frame.getContentPane().add(myPanel);

          frame.pack();                

          frame.setVisible(true);

          }

    }

 

 

/*

    *Simple2.java - 处理事件的第二种方法

    *在这个例子中,利用匿名内部类来监听每一个事件源产生的事件

    *避免使用一些if语句来决定是哪个事件源

   */

   import java.awt.*;

   import java.awt.event.*;

   import javax.swing.*;

   public class Simple2

    {

   private static JFrame frame; // 定义为静态变量以便main使用

   private static JPanel myPanel; // 该面板用来放置按钮组件

   private JButton button1;    // 这里定义按钮组件

   private JButton button2;    // 以便让ActionListener使用

   public Simple2()             // 构造器, 建立图形界面

       {

          // 新建面板

          myPanel = new JPanel();

          // 新建按钮

          button1 = new JButton("按钮1");   // 新建按钮1

          button2 = new JButton("按钮2");

          // 每一个事件源需要一个监听器

          // 定义一个匿名内部类来监听事件源产生的事件

          button1.addActionListener(

            new ActionListener()

            {

                public voidactionPerformed(ActionEvent e)

                {

                      JOptionPane.showMessageDialog(frame,

                                          "按钮1 被点击");

                }

            }

          );

          button2.addActionListener(

            new ActionListener()

            {

                public voidactionPerformed(ActionEvent e)

                {

                      JOptionPane.showMessageDialog(frame,

                                              "按钮2 被点击");

                }

            }

          );

          myPanel.add(button1);        // 添加按钮到面板

          myPanel.add(button2);

    }

   public static void main(String s[])

    {

          Simple2 gui = new Simple2(); // 新建Simple2组件

          frame = new JFrame("Simple2");   // 新建JFrame

          // 处理关闭事件的通常方法

          frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e)

                 {System.exit(0);} });

          frame.getContentPane().add(myPanel);

          frame.pack();               

          frame.setVisible(true);

          }

    }

 

 

 

   /*

    *Simple3.java - 处理事件的第三种方法

    *For this example, we will use inner member classes to

    *在这个例子中,利用一般内部类来监听每个事件源产生的事件

    *该方法避免了第二种方法中由于使用匿名内部类而导致的代码混乱

    *便于集中处理事件代码

    *每一个Hander可以被工具栏或菜单多次使用

   */

   import java.awt.*;

   import java.awt.event.*;

   import javax.swing.*;

   public class Simple3

    {

   private static JFrame frame; // 定义为静态变量以便main使用

   private static JPanel myPanel; // 该面板用来放置按钮组件

   private JButton button1;    // 这里定义按钮组件

   private JButton button2;    // 以便让ActionListener使用

   // 利用一般内部类来监听每一个事件源产生的事件如(button1,button2)

   private class Button1Handler implements ActionListener

    {

          public void actionPerformed(ActionEvent e)

          {

            JOptionPane.showMessageDialog(frame,

                                           "按钮1 被点击");

          }

    }

   private class Button2Handler implements ActionListener

    {

          public void actionPerformed(ActionEvent e)

          {

            JOptionPane.showMessageDialog(frame,

                                           "按钮2 被点击");

          }

    }

   public Simple3()            //   // 构造器, 建立图形界面

    {

         // 新建面板

          myPanel = new JPanel();

          // 新建按钮

          button1 = new JButton("按钮1");   // 新建按钮1

          button2 = new JButton("按钮2");

          // 对每一个组件注册监听内部类

          button1.addActionListener(new Button1Handler());

          button2.addActionListener(new Button2Handler());

          myPanel.add(button1);        // 添加按钮到面板

          myPanel.add(button2);

    }

   public static void main(String s[])

    {

          Simple3 gui = new Simple3();   // 新建Simple3组件

          frame = new JFrame("Simple3");   // 新建JFrame

          // 处理关闭事件的通常方法       

          frame.addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e)

                 {System.exit(0);} });

          frame.getContentPane().add(myPanel);

          frame.pack();               

          frame.setVisible(true);

          }

    }

 

 

 

可能看到这里,对Swing开发最重要的几点有了一定的认识,如果有兴趣进一步了解,可以登录我的网盘下载相关详细资料。http://115.com/file/dpvq0zjd#Swing 高级教程.doc】

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值