23.3.3 编写代码
【实例23.1】下面将举一个使用Eclipse工具来编写的代码段。在这段程序中,将创建一个登录的界面系统。
01 import javax.swing.*;
02 import java.awt.*;
03 04 public class login extends JPanel
05 {
06 static final int WIDTH=300;
07 static final int HEIGHT=150;
08 public void add(Component c, GridBagConstraints constraints, int x, int y, int w, int h)
09 {
10 constraints.gridx=x;
11 constraints.gridy=y;
12 constraints.gridwidth=w;
13 constraints.gridheight=h;
14 add(c, constraints);
15 }
16 public static void main(String[]args)
17 {
18 JFrame loginframe=new JFrame("信息管理系统");
19 loginframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20 login l=new login();
21 GridBagLayout lay=new GridBagLayout();
22 l.setLayout(lay);
23 loginframe.add(l, BorderLayout.WEST);
24 loginframe.setSize(WIDTH, HEIGHT);
25 Toolkit kit=Toolkit.getDefaultToolkit();
26 Dimension screenSize=kit.getScreenSize();
27 int width=screenSize.width;
28 int height=screenSize.height;
29 int x=(width-WIDTH)/2;
30 int y=(height-HEIGHT)/2;
31 loginframe.setLocation(x, y);
32 JButton ok=new JButton("登录");
33 JButton cancel=new JButton("放弃");
34 JLabel title=new JLabel("信息系统登录窗口");
35 JLabel name=new JLabel("用户名");
36 JLabel password=new JLabel("密码");
37 JTextField nameinput=new JTextField(15);
38 JPasswordField passwordinput=new JPasswordField(15);
39 GridBagConstraints constraints=new GridBagConstraints();
40 constraints.fill=GridBagConstraints.NONE;
41 constraints.anchor=GridBagConstraints.EAST;
42 constraints.weightx=3;
43 constraints.weighty=4;
44 l.add(title, constraints,0,0,4,1);
45 l.add(name, constraints,0,1,1,1);
46 l.add(password, constraints,0,2,1,1);
47 l.add(nameinput, constraints,2,1,1,1);
48 l.add(passwordinput, constraints,2,2,1,1);
49 l.add(ok, constraints,0,3,1,1);
50 l.add(cancel, constraints,2,3,1,1);
51 loginframe.setResizable(false);
52 loginframe.show();
53 }
54 }
【代码说明】从第32~38行可以看出这些代码是界面的组成元素,包括按钮和文本框。第37行是普通的文本框,第38行是一个密码文本框。第44~50行是将这些按钮、标签等元素添加到窗体中。第52行显示窗体。
【运行效果】将程序代码写入工作区前面创建的相应的类中。如果有错误,在图中会自动显示出来。若图中有叉叉、问号等之类的红色符号,那就是代表此语句有错误,如图23.7所示。单击工具栏中的“运行”按钮,结果如图23.8所示。
图 23.7 代码的编写
图 23.8 运行窗口