Java Swing快速构建窗体应用程序
以前接触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()方法,如下代码所示:
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 主界面
登录成功后,单击左边的树叶节点,通过反射动态实例化窗体(实际上菜单应该从数据库加载)并显示,主界面如下:

图表控件用的是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快速构建窗体应用程序的更多相关文章
- 使用eclipse和JavaFX Scene Builder进行快速构建JavaFX应用程序
http://blog.csdn.net/wingfourever/article/details/7726724 使用eclipse和JavaFX Scene Builder进行快速构建JavaFX ...
- 两小时快速构建微信小程序
小程序在2017年1月上线之初,被社会极力吹捧,刻意去将其制造为一个“风口”,透支其价值.但是在之后一个月里,石破天惊迅速归为沉寂.媒体又开始过度消费小程序,大谈其鸡肋之处. 个人认为小程序的一个分水 ...
- Java Swing 如何让窗体居中显示
如题,其他不多说,直接上代码! package com.himarking.tool; import java.awt.Toolkit; import javax.swing.JFrame; @Sup ...
- JAVA中快速构建BEAN的方法
首先,创建一个JAVA类,testBean.java. package com.beans; public class testBean { } 然后,添加私有成员字段. package com.be ...
- Java Swing设置主窗体位置居中方法
01.第一种方法 int windowWidth = frame.getWidth(); //获得窗体宽 int windowHeight = frame.getHeight(); //获得窗体高 ...
- Go通过cobra快速构建命令行应用
来自jetbrains Go 语言现状调查报告 显示:在go开发者中使用go开发实用小程序的比例为31%仅次于web,go得益于跨平台.无依赖的特性,用来编写命令行或系统管理这类小程序非常不错. 本文 ...
- atitit.窗体静听esc退出本窗体java swing c# .net php
atitit.窗体静听esc退出本窗体java swing c# .net php 1. 监听esc 按键 1 1.1. 监听一个组件 1 1.2. 监听加在form上 1 2. 关闭窗体 2 1. ...
- Java Swing窗体小工具实例 - 原创
Java Swing窗体小工具实例 1.本地webserice发布,代码如下: 1.1 JdkWebService.java package server; import java.net.InetA ...
- 如何进行Flink项目构建,快速开发Flink应用程序?
项目模板 Flink应用项目可以使用Maven或SBT来构建项目,Flink针对这些构建工具提供了相应项目模板. Maven模板命令如下,我们只需要根据提示输入应用项目的groupId.artifac ...
随机推荐
- 谈谈主函数main
我们来看一下主函数 public class HelloWorld{ public static void main(String[] args){ System.out.println(" ...
- SQL Server的日期和时间类型
Sql Server使用 Date 表示日期,time表示时间,使用datetime和datetime2表示日期和时间. 1,秒的精度是指使用多少位小数表示秒 DateTime数据类型秒的精度是3,D ...
- Microsoft Naive Bayes 算法——三国人物身份划分
Microsoft朴素贝叶斯是SSAS中最简单的算法,通常用作理解数据基本分组的起点.这类处理的一般特征就是分类.这个算法之所以称为“朴素”,是因为所有属性的重要性是一样的,没有谁比谁更高.贝叶斯之名 ...
- Ext1.X的CheckboxSelectionModel默认全选之后不允许编辑的BUG解决方案
Ext1.X的CheckboxSelectionModel默认全选之后不允许编辑的BUG解决方案,ext 的CheckboxSelectionModel在后台默认选中之后,前台就不允许编辑的bug是存 ...
- Android自定义Dialog及其布局
实际项目开发中默认的Dialog样式无法满足需求,需要自定义Dialog及其布局,并响应布局中控件的事件. 上效果图: 自定义Dialog,LogoutDialog: 要将自定义布局传入构造函数中, ...
- 轻松自动化---selenium-webdriver(python) (八)
本节重点: 调用js方法 execute_script(script, *args) 在当前窗口/框架 同步执行javaScript 脚本:JavaScript的执行. *参数:适用任何JavaScr ...
- 新人学习Android开发遇到的小问题总结
1. IDE搭建: 搭建android的IDE时,先注意是什么版本的系统,64/32位系统. 通常使用的是Eclipse for android,Android Studio由于还需要FQ,网速慢,所 ...
- 判断js数据类型和clone
判断返回js数据类型 function judgeType(arg){//判断返回js数据类型 return Object.prototype.toString.call(arg).slice(8,- ...
- 27 个免费的 HTML5/CSS3 模板供下载
EscapEvelocity Responsive Html5 Theme ( Demo || Download) Base 2013 Responsive Html5 Theme (Demo || ...
- HT for Web列表和3D拓扑组件的拖拽应用
很多可视化编辑器都或多或少有一些拖拽功能,比如从一个List列表中拖拽一个节点到拓扑组件上进行建模,并且在拖拽的过程中鼠标位置下会附带一个被拖拽节点的缩略图,那么今天我们就来实现这样的拖拽效果. 首先 ...