Java Swing快速构建窗体应用程序

时间:2023-03-08 21:33:18

  以前接触java感觉其在桌面开发上,总是不太方便,没有一个好的拖拽界面布局工具,可以快速构建窗体. 最近学习了一下NetBeans IDE 8.1,感觉其窗体设计工具还是很不错的 , 就尝试一下做了一个窗体应用程序. 总体下来,感觉和winform开发相差也不大,只是一些具体的设置或者语法有些差异,可以通过查阅相关资料进行掌握:

1 应用结构

新建一个java应用程序JavaApp,并创建相关的包及文件,其中简单实现了一个登录界面(JDBC 访问MYSQL数据库),登录成功后跳转到主界面.在主界面上单击菜单,可以打开子窗体.java swing自带的JTabbedPane没有显示关闭按钮的功能,这里在com.mkmis.controls包下自定义了一个TabbedPane控件,可以实现带关闭按钮的页签面板.应用结构如下图所示:

Java Swing快速构建窗体应用程序

2 登陆界面设计

在IDE中新建一个Login的JFrame窗体,单击[设计]视图,可以将组件面板中的相关控件拖放到界面上,和Vistual Studio的操作差别不大,就是界面显示效果较差,不及Vistual Studio.用户名文本框用的文本字段,密码框用的是口令字段控件.登录和退出按钮用的是按钮控件.

Java Swing快速构建窗体应用程序

设计完成后,单击运行按钮,界面效果如下图所示:

Java Swing快速构建窗体应用程序

3 相关属性设置

Java Swing的很多属性设置用的方法,而NET用的属性.例如设置窗体标题,java swing用的是setTitle().另外窗体居中用的是setLocationRelativeTo(getOwner()). 获取文本框的值为getText()方法,如下代码所示:

     public Login() {
initComponents();
setTitle("登录");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLocationRelativeTo(getOwner()); //居中显示 }
  private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(this.txtUserName.getText()!="" && this.txtPWD.getText().toString()!="")
{
Connection conn = DBConnection.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(
         "select * from users where UserName = ? and password = ?");
ps.setString(1,this.txtUserName.getText());//
ps.setString(2, this.txtPWD.getText());
rs = ps.executeQuery();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("UserName"));
user.setPassword(rs.getString("password")); System.out.println(user.toString());
//跳转页面
FrameMain frm=new FrameMain(user.getUsername());
frm.setVisible(true);
this.dispose();//关闭当前窗体 }
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBConnection.closeResultSet(rs);
DBConnection.closeStatement(ps);
DBConnection.closeConnection(conn);
} }
}

显示一个窗体是设置其setVisiable(true);关闭一个窗体用的dispose();在登录界面想着输完用户名和密码后,按enter键可以自动登录,在网上搜下,发现了一个变通的方法,就是监听密码框的keypressed事件,当然需要验证一下用户名和密码是否为空(此处未加验证!),如下代码所示:

    private void txtPWDKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(evt.getKeyCode()==KeyEvent.VK_ENTER)
{
//调用登录事件
btnLoginActionPerformed(null); }
}

4 主界面

登录成功后,单击左边的树叶节点,通过反射动态实例化窗体(实际上菜单应该从数据库加载)并显示,主界面如下:

Java Swing快速构建窗体应用程序

图表控件用的是JFreeChart控件,默认显示中文有乱码情况,需要设置显示中文处的字体进行解决.另外设置主界面显示最大化的代码为this.setExtendedState(this.getExtendedState()|JFrame.MAXMIZED_BOTH).为了让某个控件可以随着窗体大小变化而自动调整,需要设置其水平和垂直自动调整.

     public FrameMain(){
initComponents();
setLocationRelativeTo(getOwner()); //居中显示
this.setExtendedState(this.getExtendedState()|JFrame.MAXIMIZED_BOTH );
       //最大化 window
LoadTree(); }
public FrameMain(String uname){
initComponents();
setLocationRelativeTo(getOwner()); //居中显示
this.setExtendedState(this.getExtendedState()|JFrame.MAXIMIZED_BOTH );
LoadTree();
this.lblUser.setText("欢迎 "+uname+ " 登录!"); }

主界面在初始化时,调用LoadTree方法来填充左边的菜单树,如下所示:

     private void LoadTree()
{
//自定义控件,支持关闭按钮
jTabbedPane1.setCloseButtonEnabled(true); DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("软件部");
node1.add(new DefaultMutableTreeNode("产品部"));
node1.add(new DefaultMutableTreeNode("测试部"));
node1.add(new DefaultMutableTreeNode("设计部")); DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("销售部");
node2.add(new DefaultMutableTreeNode("jack"));
node2.add(new DefaultMutableTreeNode("Lily"));
node2.add(new DefaultMutableTreeNode("Smith")); DefaultMutableTreeNode top = new DefaultMutableTreeNode("职员管理"); top.add(new DefaultMutableTreeNode("总经理"));
top.add(node1);
top.add(node2); //JTree tree=new JTree(top);
DefaultTreeModel model = new DefaultTreeModel (top);
this.jTree1.setModel(model);
//jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION)
//set jframe icon
try {
Image icon= ImageIO.read(this.getClass().getResource("/images/Icon.png"));
tabIcon = createImageIcon("/images/Icon.png", "tab icon"); this.setIconImage(icon);
}
catch(IOException ex)
{ System.out.println(ex); } }

在Tree的值变化事件中,通过class.forName()和 cls.newInstance()反射动态实例化窗体,代码如下:

     private void jTree1ValueChanged(javax.swing.event.TreeSelectionEvent evt) {
// TODO add your handling code here: DefaultMutableTreeNode node = (DefaultMutableTreeNode)
        jTree1.getLastSelectedPathComponent(); if (node == null){
//Nothing is selected.
return;
} Object nodeInfo = node.getUserObject();
String item = (String) nodeInfo; if (node.isLeaf()) {
String item1 = (String) nodeInfo;
// this.setTitle(item1);
//File f = new File("client.jar");
//URLClassLoader cl = new URLClassLoader(new URL[]{f.toURI().toURL(), null});
//Class<?> clazz = cl.loadClass("epicurus.Client");
//Method main = clazz.getMethod("main", String[].class);
//main.invoke(null, new Object[]{new String[]{}});
try {
Class cls = Class.forName("com.mkmis.forms.JIFrame1");
javax.swing.JInternalFrame frm =
                (javax.swing.JInternalFrame) cls.newInstance();
frm.setVisible(true); //jTabbedPane1.addTab(" "+item1+" ",null,frm);
jTabbedPane1.addTab(" "+item1+" ",this.tabIcon,frm); }
catch (Throwable e) {
System.err.println(e);
}
} else {
System.out.println("not leaf");
}
}

在javaswing中的路径也和net不同,下面定义了一个创建ImageIcon的方法:

     /** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}

5 JDBC MYSQL代码

 package com.mkmis.db;

 import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; public class DBConnection { public static Connection getConnection() {
Properties props = new Properties();
FileInputStream fis = null;
Connection con = null;
try {
fis = new FileInputStream("db.properties");
props.load(fis);
//
Class.forName(props.getProperty("DB_DRIVER_CLASS"));
//
con = DriverManager.getConnection(props.getProperty("DB_URL"), props.getProperty("DB_USERNAME"), props.getProperty("DB_PASSWORD"));
} catch (IOException | SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return con;
} // �ر�ResultSet
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
} //Statement
public static void closeStatement(Statement stm) {
if (stm != null) {
try {
stm.close();
stm = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
} //PreparedStatement
public static void closePreparedStatement(PreparedStatement pstm) {
if (pstm != null) {
try {
pstm.close();
pstm = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
} //Connection
public static void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
con = null;
} catch (SQLException e) {
e.printStackTrace();
}
con = null;
}
} }

6 图表窗体代码

 /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mkmis.forms; import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font; import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
//import org.jfree.ui.ApplicationFrame;
//import org.jfree.ui.RefineryUtilities;
/**
*
* @author wangming
*/
public class JIFrame1 extends javax.swing.JInternalFrame { /**
* Creates new form JIFrame1
*/
public JIFrame1() {
initComponents();
//hiding title bar of JInternalFrame
((javax.swing.plaf.basic.BasicInternalFrameUI)this.getUI()).setNorthPane(null);
this.setBackground(Color.white); CategoryDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setFillZoomRectangle(true);
chartPanel.setMouseWheelEnabled(true);
chartPanel.setPreferredSize(new Dimension(500, 270));
setContentPane(chartPanel);
} /**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() { setBorder(null);
setClosable(true);
setMaximizable(true);
setResizable(true); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 410, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 285, Short.MAX_VALUE)
); pack();
}// </editor-fold> private static final long serialVersionUID = 1L; static {
// set a theme using the new shadow generator feature available in
// 1.0.14 - for backwards compatibility it is not enabled by default
ChartFactory.setChartTheme(new StandardChartTheme("JFree/Shadow",
true));
} /**
* Creates a new demo instance.
*
* @param title the frame title.
*/
public JIFrame1(String title) {
super(title);
CategoryDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setFillZoomRectangle(true);
chartPanel.setMouseWheelEnabled(true);
chartPanel.setPreferredSize(new Dimension(500, 270));
setContentPane(chartPanel);
} /**
* Returns a sample dataset.
*
* @return The dataset.
*/
private static CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(7445, "JFreeSVG", "Warm-up");
dataset.addValue(24448, "Batik", "Warm-up");
dataset.addValue(4297, "JFreeSVG", "Test");
dataset.addValue(21022, "Batik", "Test");
return dataset;
} /**
* Creates a sample chart.
*
* @param dataset the dataset.
*
* @return The chart.
*/
private static JFreeChart createChart(CategoryDataset dataset) {
//中文乱码,设置字体
Font font=new Font("微软雅黑",Font.BOLD,18);//测试是可以的 JFreeChart chart = ChartFactory.createBarChart("性能: JFreeSVG 对比 Batik", null /* x-axis label*/,
"毫秒" /* y-axis label */, dataset);
//中文乱码,设置字体
chart.getTitle().setFont(font); chart.addSubtitle(new TextTitle("在SVG中产生1000个图表"));
chart.setBackgroundPaint(Color.white);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setLabelFont(font); CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setLabelFont(font);
// ******************************************************************
// More than 150 demo applications are included with the JFreeChart
// Developer Guide...for more information, see:
//
// > http://www.object-refinery.com/jfreechart/guide.html
//
// ****************************************************************** rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
chart.getLegend().setFrame(BlockBorder.NONE);
return chart;
} /**
* Starting point for the demonstration application.
*
* @param args ignored.
*/
// public static void main(String[] args) {
// BarChartDemo1 demo = new BarChartDemo1("JFreeChart: BarChartDemo1.java");
// demo.pack();
// RefineryUtilities.centerFrameOnScreen(demo);
// demo.setVisible(true);
// } // Variables declaration - do not modify
// End of variables declaration
}

运行此app,一定要引入需要的库,mysql jdbc驱动和jfreechart库

Java Swing快速构建窗体应用程序