学习Java桌面应用程序开发_主窗体
一般的应用程序都是登陆窗体,登陆成功后进入主界面的,先看看主界面的草图:
从图中可以看出,主界面大致可以分为四块,上面是菜单栏及图片工具栏,左边是树形导航,下边的状态栏。
菜单栏:JMenuBar(菜单条),JMenu(菜单),JMenuItem (菜单项)
工具条:toolbar,JButton(按钮+图片)
树形导航:JTree
状态栏:toolbar,JLable
实现界面的代码:
菜单栏:
代码
1 finalJMenuBar menuBar=newJMenuBar();2 menuBar.setName("menuBar");3 setJMenuBar(menuBar);4 5 finalJMenu jmenuFile=newJMenu();6 jmenuFile.setText("文件(F)");7 jmenuFile.setName("menuFile");8 menuBar.add(jmenuFile);9 10 finalJMenuItem newProject=newJMenuItem();11 newProject.setName("newProject");12 newProject.setText("新建工程");13 jmenuFile.add(newProject);14 15 finalJMenu jmenuTool=newJMenu();16 jmenuTool.setText("工具(T)");17 jmenuTool.setName("jmenuTool");18 menuBar.add(jmenuTool);
工具栏:
代码
finalJToolBar toolBar=newJToolBar();
toolBar.setName("toolBar");
getContentPane().add(toolBar, BorderLayout.NORTH);finalJButton jbtnNew=newJButton();
jbtnNew.addActionListener(newActionListener() {publicvoidactionPerformed(finalActionEvent arg0) {//点击新建按钮触发事件}
});
jbtnNew.setName("jbtnNew");
jbtnNew.setIcon(SwingResourceManager.getIcon(Main.class,"Image/FileNew.png"));
jbtnNew.setText("新建");
toolBar.add(jbtnNew);
toolBar.addSeparator();finalJButton jbtnSave=newJButton();
jbtnSave.addActionListener(newActionListener() {publicvoidactionPerformed(finalActionEvent arg0) {
}
});
jbtnSave.setName("jbtnSave");
jbtnSave.setIcon(SwingResourceManager.getIcon(Main.class,"Image/FileSave.png"));
jbtnSave.setText("保存");
toolBar.add(jbtnSave);
树形菜单:
//根节点DefaultMutableTreeNode root=newDefaultMutableTreeNode("任务信息");//创建树JTree tree=newJTree(root);
状态栏:
代码
1 finalJToolBar stautsBar=newJToolBar();2 stautsBar.setName("statusBar");3 getContentPane().add(stautsBar, BorderLayout.SOUTH);4 5 lblWelcome=newJLabel();6 lblWelcome.setText("欢迎");7 stautsBar.add(lblWelcome);8 9 stautsBar.addSeparator();10 11 lblSupport=newJLabel();12 lblSupport.setText("技术支持:");13 stautsBar.add(lblSupport);
利用上述代码 就可以搭出主界面的框架来,可能还需要朋友们自己去扩展。。
注意:
1、要注意界面的布局,可以添加jpanel容器参与布局。
2、现在看到的草图控件是比较少的,如果控件多了,处理的事件多了,那么就为了防止主界面代码过多,就需要我们学会使用分拆分,再组合的方式。
例如:树形控件或处理事件的代码 成一个类(test1)
面板1控件或处理事件的代码一个类(test2)
。。。。。。
主界面中时 组合在一起 效果是一样的 但是主界面的代码将大大减少。。
3、在新建一个jframe后,一定要为界面编写释放资源的代码,如果你不编写dispose(); 运行一次 就会在进程中添加一个javaw进程(可以自己测试)
public void windowClosing(final WindowEvent e) {
dispose();
}