以前接触java感觉其在桌面开发上,总是不太方便,没有一个好的拖拽界面布局工具,可以快速构建窗体. 最近学习了一下NetBeans IDE 8.1,感觉其窗体设计工具还是很不错的 , 就尝试一下做了一个窗体应用程序. 总体下来,感觉和winform开发相差也不大,只是一些具体的设置或者语法有些差异,可以通过查阅相关资料进行掌握:
1 应用结构
新建一个java应用程序JavaApp,并创建相关的包及文件,其中简单实现了一个登录界面(JDBC 访问MySQL数据库),登录成功后跳转到主界面.在主界面上单击菜单,可以打开子窗体.java swing自带的JTabbedPane没有显示关闭按钮的功能,这里在com.mkmis.controls包下自定义了一个TabbedPane控件,可以实现带关闭按钮的页签面板.应用结构如下图所示:
2 登陆界面设计
在IDE中新建一个Login的JFrame窗体,单击[设计]视图,可以将组件面板中的相关控件拖放到界面上,和Vistual Studio的操作差别不大,就是界面显示效果较差,不及Vistual Studio.用户名文本框用的文本字段,密码框用的是口令字段控件.登录和退出按钮用的是按钮控件.
设计完成后,单击运行按钮,界面效果如下图所示:
3 相关属性设置
Java Swing的很多属性设置用的方法,而NET用的属性.例如设置窗体标题,java swing用的是setTitle().另外窗体居中用的是setLocationRelativeTo(getOwner()). 获取文本框的值为getText()方法,如下代码所示:
1publicLogin() {2initComponents();3setTitle("登录");4setDefaultCloSEOperation(EXIT_ON_CLOSE);5setVisible(true);6setResizable(false);7setLocationRelativeTo(getOwner());//居中显示89}
1PRivatevoidbtnLoginActionPerformed(java.awt.event.ActionEvent evt) {2//TODO add your handling code here:3if(this.txtUserName.getText()!="" &&this.txtPWD.getText().toString()!="")4{5Connection conn =DBConnection.getConnection();6PreparedStatement ps =null;7ResultSet rs =null;8try{9ps = conn.prepareStatement(
"select * from users where UserName = ? and passWord= ?");10ps.setString(1,this.txtUserName.getText());//11ps.setString(2,this.txtPWD.getText());12rs =ps.executeQuery();13while(rs.next()) {14User user =newUser();15user.setId(rs.getInt("id"));16user.setUsername(rs.getString("UserName"));17user.setPassword(rs.getString("password"));1819System.out.println(user.toString());20//跳转页面21FrameMain frm=newFrameMain(user.getUsername());22frm.setVisible(true);23this.dispose();//关闭当前窗体2425}26}catch(SQLException e) {27e.printStackTrace();28}finally{29DBConnection.closeResultSet(rs);30DBConnection.closeStatement(ps);31DBConnection.closeConnection(conn);32}3334}35}
显示一个窗体是设置其setVisiable(true);关闭一个窗体用的dispose();在登录界面想着输完用户名和密码后,按enter键可以自动登录,在网上搜下,发现了一个变通的方法,就是监听密码框的keypressed事件,当然需要验证一下用户名和密码是否为空(此处未加验证!),如下代码所示:
1privatevoidtxtPWDKeyPressed(java.awt.event.KeyEvent evt) {2//TODO add your handling code here:3if(evt.getKeyCode()==KeyEvent.VK_ENTER)4{5//调用登录事件6btnLoginActionPerformed(null);78}9}
4 主界面
登录成功后,单击左边的树叶节点,通过反射动态实例化窗体(实际上菜单应该从数据库加载)并显示,主界面如下:
图表控件用的是JFreeChart控件,默认显示中文有乱码情况,需要设置显示中文处的字体进行解决.另外设置主界面显示最大化的代码为this.setExtendedState(this.getExtendedState()|JFrame.MAXMIZED_BOTH).为了让某个控件可以随着窗体大小变化而自动调整,需要设置其水平和垂直自动调整.
1publicFrameMain(){2initComponents();3setLocationRelativeTo(getOwner());//居中显示4this.setExtendedState(this.getExtendedState()|JFrame.MAXIMIZED_BOTH );
//最大化 window5LoadTree();67}8publicFrameMain(String uname){9initComponents();10setLocationRelativeTo(getOwner());//居中显示11this.setExtendedState(this.getExtendedState()|JFrame.MAXIMIZED_BOTH );12LoadTree();13this.lblUser.setText("欢迎 "+uname+ " 登录!");1415}
主界面在初始化时,调用LoadTree方法来填充左边的菜单树,如下所示:
1privatevoidLoadTree()2{3//自定义控件,支持关闭按钮4jTabbedPane1.setCloseButtonEnabled(true);56DefaultMutableTreeNode node1 =newDefaultMutableTreeNode("软件部");7node1.add(newDefaultMutableTreeNode("产品部"));8node1.add(newDefaultMutableTreeNode("测试部"));9node1.add(newDefaultMutableTreeNode("设计部"));1011DefaultMutableTreeNode node2 =newDefaultMutableTreeNode("销售部");12node2.add(newDefaultMutableTreeNode("jack"));13node2.add(newDefaultMutableTreeNode("Lily"));14node2.add(newDefaultMutableTreeNode("Smith"));1516DefaultMutableTreeNode top =newDefaultMutableTreeNode("职员管理");171819top.add(newDefaultMutableTreeNode("总经理"));20top.add(node1);21top.add(node2);2223//JTree tree=new JTree(top);24DefaultTreeModel model =newDefaultTreeModel (top);25this.jTree1.setModel(model);26//jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION)27//set jframe icon28try2930{31Image icon= ImageIO.read(this.getClass().getResource("/images/Icon.png"));32tabIcon = createImageIcon("/images/Icon.png", "tab icon");3334this.setIconImage(icon);35}36catch(IOException ex)37{3839System.out.println(ex);4041}4243}
在Tree的值变化事件中,通过class.forName()和 cls.newInstance()反射动态实例化窗体,代码如下:
1privatevoidjTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {2//TODO add your handling code here:34DefaultMutableTreeNode node =(DefaultMutableTreeNode)
jTree1.getLastSelectedPathComponent();56if(node ==null){7//Nothing is selected.8return;9}1011Object nodeInfo =node.getUserObject();12String item =(String) nodeInfo;1314if(node.isLeaf()) {15String item1 =(String) nodeInfo;16//this.setTitle(item1);17//File f = new File("client.jar");18//URLClassLoader cl = new URLClassLoader(new URL[]{f.toURI().toURL(), null});19//Class<?> clazz = cl.loadClass("epicurus.Client");20//Method main = clazz.getMethod("main", String[].class);21//main.invoke(null, new Object[]{new String[]{}});22try{23Class cls = Class.forName("com.mkmis.forms.JIFrame1");24javax.swing.JInternalFrame frm =
(javax.swing.JInternalFrame) cls.newInstance();25frm.setVisible(true);2627//jTabbedPane1.addTab(" "+item1+" ",null,frm);28jTabbedPane1.addTab(" "+item1+" ",this.tabIcon,frm);2930}31catch(Throwable e) {32System.err.println(e);33}34}else{35System.out.println("not leaf");36}37}
在javaswing中的路径也和net不同,下面定义了一个创建ImageIcon的方法:
1/**Returns an ImageIcon, or null if the path was invalid.*/2protectedImageIcon createImageIcon(String path,String description) {3java.net.URL imgURL =getClass().getResource(path);4if(imgURL !=null) {5returnnewImageIcon(imgURL, description);6}else{7System.err.println("Couldn't find file: " +path);8returnnull;9}10}
5 JDBC MYSQL代码
1packagecom.mkmis.db;23importjava.io.FileInputStream;4importjava.io.IOException;5importjava.sql.Connection;6importjava.sql.DriverManager;7importjava.sql.PreparedStatement;8importjava.sql.ResultSet;9importjava.sql.SQLException;10importjava.sql.Statement;11importjava.util.Properties;121314publicclassDBConnection {1516publicstaticConnection getConnection() {17Properties props =newProperties();18FileInputStream fis =null;19Connection con =null;20try{21fis =newFileInputStream("db.properties");22props.load(fis);23//24Class.forName(props.getProperty("DB_DRIVER_CLASS"));25//26con = DriverManager.getConnection(props.getProperty("DB_URL"), props.getProperty("DB_USERNAME"), props.getProperty("DB_PASSWORD"));27}catch(IOException | SQLException |ClassNotFoundException e) {28e.printStackTrace();29}30returncon;31}3233//�ر�ResultSet34publicstaticvoidcloseResultSet(ResultSet rs) {35if(rs !=null) {36try{37rs.close();38rs =null;39}catch(SQLException e) {40e.printStackTrace();41}42}43}4445//Statement46publicstaticvoidcloseStatement(Statement stm) {47if(stm !=null) {48try{49stm.close();50stm =null;51}catch(SQLException e) {52e.printStackTrace();53}54}55}5657//PreparedStatement58publicstaticvoidclosePreparedStatement(PreparedStatement pstm) {59if(pstm !=null) {60try{61pstm.close();62pstm =null;63}catch(SQLException e) {64e.printStackTrace();65}66}67}6869//Connection70publicstaticvoidcloseConnection(Connection con) {71if(con !=null) {72try{73con.close();74con =null;75}catch(SQLException e) {76e.printStackTrace();77}78con =null;79}80}8182}
View Code
6 图表窗体代码
1/*2* To change this license header, choose License Headers in Project Properties.3* To change this template file, choose Tools | Templates4* and open the template in the editor.5*/6packagecom.mkmis.forms;78importjava.awt.Color;9importjava.awt.Dimension;10importjava.awt.Font;1112importorg.jfree.chart.ChartFactory;13importorg.jfree.chart.ChartPanel;14importorg.jfree.chart.JFreeChart;15importorg.jfree.chart.StandardChartTheme;16importorg.jfree.chart.axis.CategoryAxis;17importorg.jfree.chart.axis.NumberAxis;18importorg.jfree.chart.block.BlockBorder;19importorg.jfree.chart.plot.CategoryPlot;20importorg.jfree.chart.renderer.category.BarRenderer;21importorg.jfree.chart.title.TextTitle;22importorg.jfree.data.category.CategoryDataset;23importorg.jfree.data.category.DefaultCategoryDataset;24//import org.jfree.ui.applicationFrame;25//import org.jfree.ui.RefineryUtilities;26/**27*28*@authorwangming29*/30publicclassJIFrame1extendsjavax.swing.JInternalFrame {3132/**33* Creates new form JIFrame134*/35publicJIFrame1() {36initComponents();37//hiding title bar of JInternalFrame38((javax.swing.plaf.basic.BasicInternalFrameUI)this.getUI()).setNorthPane(null);39this.setBackground(Color.white);4041CategoryDataset dataset =createDataset();42JFreeChart chart =createChart(dataset);43ChartPanel chartPanel =newChartPanel(chart);44chartPanel.setFillZoomRectangle(true);45chartPanel.setMouseWheelEnabled(true);46chartPanel.setPreferredSize(newDimension(500, 270));47setContentPane(chartPanel);48}4950/**51* This method is called from within the constructor to initialize the form.52* WARNING: Do NOT modify this code. The content of this method is always53* regenerated by the Form Editor.54*/55@SuppressWarnings("unchecked")56//<editor-fold defaultstate="collapsed" desc="Generated Code">57privatevoidinitComponents() {5859setBorder(null);60setClosable(true);61setMaximizable(true);62setResizable(true);6364javax.swing.GroupLayout layout =newjavax.swing.GroupLayout(getContentPane());65getContentPane().setLayout(layout);66layout.setHorizontalGroup(67layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)68.addGap(0, 410, Short.MAX_VALUE)69);70layout.setVerticalGroup(71layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)72.addGap(0, 285, Short.MAX_VALUE)73);7475pack();76}//</editor-fold>7778privatestaticfinallongserialVersionUID = 1L;7980static{81//set a theme using the new shadow generator feature available in82//1.0.14 - for backwards compatibility it is not enabled by default83ChartFactory.setChartTheme(newStandardChartTheme("JFree/Shadow",84true));85}8687/**88* Creates a new demo instance.89*90*@paramtitle the frame title.91*/92publicJIFrame1(String title) {93super(title);94CategoryDataset dataset =createDataset();95JFreeChart chart =createChart(dataset);96ChartPanel chartPanel =newChartPanel(chart);97chartPanel.setFillZoomRectangle(true);98chartPanel.setMouseWheelEnabled(true);99chartPanel.setPreferredSize(newDimension(500, 270));100setContentPane(chartPanel);101}102103/**104* Returns a sample dataset.105*106*@returnThe dataset.107*/108privatestaticCategoryDataset createDataset() {109DefaultCategoryDataset dataset =newDefaultCategoryDataset();110dataset.addValue(7445, "JFreeSVG", "Warm-up");111dataset.addValue(24448, "Batik", "Warm-up");112dataset.addValue(4297, "JFreeSVG", "Test");113dataset.addValue(21022, "Batik", "Test");114returndataset;115}116117/**118* Creates a sample chart.119*120*@paramdataset the dataset.121*122*@returnThe chart.123*/124privatestaticJFreeChart createChart(CategoryDataset dataset) {125//中文乱码,设置字体126Font font=newFont("微软雅黑",Font.BOLD,18);//测试是可以的127128129130131JFreeChart chart = ChartFactory.createBarChart("性能: JFreeSVG 对比 Batik",null/*x-axis label*/,132"毫秒"/*y-axis label*/, dataset);133//中文乱码,设置字体134chart.getTitle().setFont(font);135136chart.addSubtitle(newTextTitle("在SVG中产生1000个图表"));137chart.setBackgroundPaint(Color.white);138CategoryPlot plot =(CategoryPlot) chart.getPlot();139NumberAxis rangeAxis =(NumberAxis) plot.getRangeAxis();140rangeAxis.setLabelFont(font);141142CategoryAxis domainAxis =plot.getDomainAxis();143domainAxis.setLabelFont(font);144//******************************************************************145//More than 150 demo applications are included with the JFreeChart146//Developer Guide...for more information, see:147//148//>http://www.object-refinery.com/jfreechart/guide.html149//150//******************************************************************151152153rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());154BarRenderer renderer =(BarRenderer) plot.getRenderer();155renderer.setDrawBarOutline(false);156chart.getLegend().setFrame(BlockBorder.NONE);157returnchart;158}159160/**161* Starting point for the demonstration application.162*163*@paramargs ignored.164*/165//public static void main(String[] args) {166//BarChartDemo1 demo = new BarChartDemo1("JFreeChart: BarChartDemo1.java");167//demo.pack();168//RefineryUtilities.centerFrameOnScreen(demo);169//demo.setVisible(true);170//}171172//Variables declaration - do not modify173//End of variables declaration174}
View Code
运行此app,一定要引入需要的库,mysql jdbc驱动和jfreechart库