java常用代码

来源:互联网 发布:c语言二叉查找树 编辑:程序博客网 时间:2024/05/01 05:22
java访问xml文件
Java code
import java.io.*;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;public class xmljava{ public static void main(String args[]) { Element element=null; File f =new File("a.xml"); DocumentBuilder db=null; //documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件) DocumentBuilderFactory dbf=null; try{ dbf= DocumentBuilderFactory.newInstance(); //返回documentBuilderFactory对象 db =dbf.newDocumentBuilder();//返回db对象用documentBuilderFatory对象获得返回documentBuildr对象 Document dt= db.parse(f); //得到一个DOM并返回给document对象 element = dt.getDocumentElement();//得到一个elment根元素 System.out.println("根元素:"+element.getNodeName()); //获得根节点 NodeList childNodes =element.getChildNodes() ; // 获得根元素下的子节点 for (int i = 0; i < childNodes.getLength(); i++) // 遍历这些子节点 { Node node1 = childNodes.item(i); // childNodes.item(i); 获得每个对应位置i的结点 if ("Account".equals(node1.getNodeName())) { // 如果节点的名称为"Account",则输出Account元素属性type System.out.println("\r\n找到一篇账号. 所属区域: " + node1.getAttributes().getNamedItem ("type").getNodeValue() + ". "); NodeList nodeDetail = node1.getChildNodes(); // 获得<Accounts>下的节点 for (int j = 0; j < nodeDetail.getLength(); j++) { // 遍历<Accounts>下的节点 Node detail = nodeDetail.item(j); // 获得<Accounts>元素每一个节点 if ("code".equals(detail.getNodeName())) // 输出code System.out.println("卡号: " + detail.getTextContent()); else if ("pass".equals(detail.getNodeName())) // 输出pass System.out.println("密码: " + detail.getTextContent()); else if ("name".equals(detail.getNodeName())) // 输出name System.out.println("姓名: " + detail.getTextContent()); else if ("money".equals(detail.getNodeName())) // 输出money System.out.println("余额: "+ detail.getTextContent()); } } }}catch(Exception e){System.out.println(e);} }}

XML code
<?xml version="1.0" encoding="gbk"?> <Accounts><Account type="by0003"> <code>100001</code><pass>123</pass><name>李四</name> <money>1000000.00</money> </Account> <Account type="hz0001"> <code>100002</code><pass>123</pass><name>张三</name> <money>1000.00</money> </Account> </Accounts>

   

 

  • 等 级:
#1楼 得分:0回复于:2011-03-31 23:23:18
java jdbc数据库连接
Java code
import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class JDBConnection { public Connection conn = null; // 声明Connection对象的实例 public Statement stmt = null; // 声明Statement对象的实例 public ResultSet rs = null; // 声明ResultSet对象的实例 private static String dbClassName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";//定义保存数据库驱动的变量 private static String dbUrl = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=DB_ATM"; private static String dbUser = "sa"; private static String dbPwd = "sa"; public JDBConnection(String propertyFileName) {// 带属性文件名的构造方法 Properties prop = new Properties();// 属性集合对象 InputStream is = null; try { is = JDBConnection.class.getClassLoader().getResourceAsStream( propertyFileName);// 属性文件输入流 // is = new FileInputStream("src/" + propertyFileName); prop.load(is);// 将属性文件流装载到Properties对象中 is.close();// 关闭流 dbClassName = prop.getProperty("dbClassName"); dbUrl = prop.getProperty("dbUrl"); dbUser = prop.getProperty("dbUser"); dbPwd = prop.getProperty("dbPwd"); } catch (Exception e) { System.out.println("属性文件 " + propertyFileName + " 打开失败!"); } try { Class.forName(dbClassName);// 1.注册驱动 } catch (ClassNotFoundException e) { e.printStackTrace(); } } public JDBConnection() {// 默认的不带参数的构造函数 try { Class.forName(dbClassName);// 1.注册驱动 } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() { Connection conn = null; try { // Class.forName(dbClassName);// 1.注册驱动 conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd);//2.建立与数据库的链接 } catch (Exception ee) { ee.printStackTrace(); } if (conn == null) { System.err .println("警告: DbConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:" + dbClassName + "\r\n链接位置:" + dbUrl + "\r\n用户/密码" + dbUser + "/" + dbPwd); } return conn; } /* * 功能:执行查询语句 */ public ResultSet executeQuery(String sql) { try { // 捕捉异常 conn = getConnection(); // 调用getConnection()方法构造Connection对象的一个实例conn stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,//3.创建语句 ResultSet.CONCUR_READ_ONLY); rs = stmt.executeQuery(sql);//4.执行查询 } catch (SQLException ex) { System.err.println(ex.getMessage()); // 输出异常信息 } return rs; // 返回结果集对象 5.结果处理 } /* * 功能:执行更新操作 */ public int executeUpdate(String sql) { int result = 0; // 定义保存返回值的变量 try { // 捕捉异常 conn = getConnection(); // 调用getConnection()方法构造Connection对象的一个实例conn stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); result = stmt.executeUpdate(sql); // 执行更新操作 } catch (SQLException ex) { result = 0; // 将保存返回值的变量赋值为0 } return result; // 返回保存返回值的变量 } /* * 功能:关闭数据库的连接 */ public void close() {//6.释放资源 try { // 捕捉异常 try { if (rs != null) { // 当ResultSet对象的实例rs不为空时 rs.close(); // 关闭ResultSet对象 } } finally { try { if (stmt != null) { // 当Statement对象的实例stmt不为空时 stmt.close(); // 关闭Statement对象 } } finally { if (conn != null) { // 当Connection对象的实例conn不为空时 conn.close(); // 关闭Connection对象 } } } } catch (Exception e) { e.printStackTrace(System.err); // 输出异常信息 } }}

属性文件
dbClassName=com.microsoft.jdbc.sqlserver.SQLServerDriver
dbClassName2=com.mysql.jdbc.Driver
dbPwd=sa
dbPwd2=root
dbUrl=jdbc\:microsoft\:sqlserver\://localhost\:1433;DatabaseName\=DB_ATM
dbUrl2=jdbc\:mysql\://localhost\:3306/db_atm
dbUser=sa
dbUser2=root
 
  • 对我有用[9]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
  • afgasdg用户头像
  • afgasdg
  • (米林)
  • 等 级:
#3楼 得分:0回复于:2011-03-31 23:25:11
java自定义按钮外观
Java code
import java.awt.FlowLayout;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.UIManager;import javax.swing.plaf.synth.SynthLookAndFeel; public class MyButton { JFrame frame = new JFrame("Test Buttons"); JButton jButton = new JButton("JButton"); // 按钮 public MyButton() { frame.setLayout(new FlowLayout()); frame.getContentPane().add(jButton); } public void show() { frame.pack(); frame.show(); } public static void main(String[] args) { MyButton tb = new MyButton(); tb.show(); SynthLookAndFeel slf = new SynthLookAndFeel(); try { slf.load(MyButton.class.getResourceAsStream("mybutton.xml"), MyButton.class); UIManager.setLookAndFeel(slf); } catch (Exception e) { e.printStackTrace(); return; } }}

XML code
<synth> <style id="mybutton"> <state> <imagePainter method="buttonBackground" path="mybutton.png" sourceInsets="3 6 12 20" paintCenter="true" stretch="true"/> <insets top="3" left="6" bottom="12" right="20"/> <font name="Aharoni" size="16"/> </state> <property key="Button.margin" type="insets" value="0 0 5 8"/> </style> <bind style="mybutton" type="region" key="Button"/></synth>
 
  • 对我有用[5]
  • 丢个板砖[1]
  • 引用
  • 举报
  • 管理
  • TOP
  • afgasdg用户头像
  • afgasdg
  • (米林)
  • 等 级:
#4楼 得分:0回复于:2011-03-31 23:26:41
java访问资源文件
Java code
import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; public class PropertyEditor { public static void main(String[] args) throws Exception { Properties prop = new Properties();// 属性集合对象 FileInputStream fis = new FileInputStream("prop.properties");// 属性文件输入流 (相对于根目录下的文件名,要加上包名 “src/prop.properties”) prop.load(fis);// 将属性文件流装载到Properties对象中 fis.close();// 关闭流 // 获取属性值,sitename已在文件中定义 System.out.println("获取属性值:sitename=" + prop.getProperty("sitename")); // 获取属性值,country未在文件中定义,将在此程序中返回一个默认值,但并不修改属性文件 System.out.println("获取属性值:country=" + prop.getProperty("country", "中国")); // 修改sitename的属性值 prop.setProperty("sitename", "中国"); // 添加一个新的属性studio prop.setProperty("studio", "Boxcode Studio"); // 文件输出流 FileOutputStream fos = new FileOutputStream("prop.properties"); // 将Properties集合保存到流中 prop.store(fos, "Copyright (c) Boxcode Studio"); fos.close();// 关闭流 } }


资源文件

sitename=\u4E2D\u56FD
siteurl=www.abcjava.com  
studio=Boxcode Studio
 
  • 对我有用[7]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
  • drg202用户头像
  • drg202
  • (drg202)
  • 等 级:
#5楼 得分:0回复于:2011-03-31 23:33:31
先收藏先,以后有用得着的地方。
 
  • 对我有用[1]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
  • afgasdg用户头像
  • afgasdg
  • (米林)
  • 等 级:
#6楼 得分:0回复于:2011-03-31 23:36:08
java日期处理bean
Java code
import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.regex.Pattern;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;public class DateUtil { protected static Log logger = LogFactory.getLog(DateUtil.class); // 格式:年-月-日 小时:分钟:秒 public static final String FORMAT_ONE = "yyyy-MM-dd HH:mm:ss"; // 格式:年-月-日 小时:分钟 public static final String FORMAT_TWO = "yyyy-MM-dd HH:mm"; // 格式:年月日 小时分钟秒 public static final String FORMAT_THREE = "yyyyMMdd-HHmmss"; // 格式:年-月-日 public static final String LONG_DATE_FORMAT = "yyyy-MM-dd"; // 格式:月-日 public static final String SHORT_DATE_FORMAT = "MM-dd"; // 格式:小时:分钟:秒 public static final String LONG_TIME_FORMAT = "HH:mm:ss"; //格式:年-月 public static final String MONTG_DATE_FORMAT = "yyyy-MM"; // 年的加减 public static final int SUB_YEAR = Calendar.YEAR; // 月加减 public static final int SUB_MONTH = Calendar.MONTH; // 天的加减 public static final int SUB_DAY = Calendar.DATE; // 小时的加减 public static final int SUB_HOUR = Calendar.HOUR; // 分钟的加减 public static final int SUB_MINUTE = Calendar.MINUTE; // 秒的加减 public static final int SUB_SECOND = Calendar.SECOND; static final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; @SuppressWarnings("unused") private static final SimpleDateFormat timeFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); public DateUtil() { } /** * 把符合日期格式的字符串转换为日期类型 */ public static java.util.Date stringtoDate(String dateStr, String format) { Date d = null; SimpleDateFormat formater = new SimpleDateFormat(format); try { formater.setLenient(false); d = formater.parse(dateStr); } catch (Exception e) { // log.error(e); d = null; } return d; } /** * 把符合日期格式的字符串转换为日期类型 */ public static java.util.Date stringtoDate(String dateStr, String format, ParsePosition pos) { Date d = null; SimpleDateFormat formater = new SimpleDateFormat(format); try { formater.setLenient(false); d = formater.parse(dateStr, pos); } catch (Exception e) { d = null; } return d; } /** * 把日期转换为字符串 */ public static String dateToString(java.util.Date date, String format) { String result = ""; SimpleDateFormat formater = new SimpleDateFormat(format); try { result = formater.format(date); } catch (Exception e) { // log.error(e); } return result; } /** * 获取当前时间的指定格式 */ public static String getCurrDate(String format) { return dateToString(new Date(), format); } public static String dateSub(int dateKind, String dateStr, int amount) { Date date = stringtoDate(dateStr, FORMAT_ONE); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(dateKind, amount); return dateToString(calendar.getTime(), FORMAT_ONE); } /** * 两个日期相减 * @return 相减得到的秒数 */ public static long timeSub(String firstTime, String secTime) { long first = stringtoDate(firstTime, FORMAT_ONE).getTime(); long second = stringtoDate(secTime, FORMAT_ONE).getTime(); return (second - first) / 1000; } /** * 获得某月的天数 */ public static int getDaysOfMonth(String year, String month) { int days = 0; if (month.equals("1") || month.equals("3") || month.equals("5") || month.equals("7") || month.equals("8") || month.equals("10") || month.equals("12")) { days = 31; } else if (month.equals("4") || month.equals("6") || month.equals("9") || month.equals("11")) { days = 30; } else { if ((Integer.parseInt(year) % 4 == 0 && Integer.parseInt(year) % 100 != 0) || Integer.parseInt(year) % 400 == 0) { days = 29; } else { days = 28; } } return days; } /** * 获取某年某月的天数 */ public static int getDaysOfMonth(int year, int month) { Calendar calendar = Calendar.getInstance(); calendar.set(year, month - 1, 1); return calendar.getActualMaximum(Calendar.DAY_OF_MONTH); } /** * 获得当前日期 */ public static int getToday() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.DATE); } /** * 获得当前月份 */ public static int getToMonth() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.MONTH) + 1; } /** * 获得当前年份 */ public static int getToYear() { Calendar calendar = Calendar.getInstance(); return calendar.get(Calendar.YEAR); } /** * 返回日期的天 */ public static int getDay(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DATE); } /** * 返回日期的年 */ public static int getYear(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } /** * 返回日期的月份,1-12 */ public static int getMonth(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.MONTH) + 1; } /** * 计算两个日期相差的天数,如果date2 > date1 返回正数,否则返回负数 */ public static long dayDiff(Date date1, Date date2) { return (date2.getTime() - date1.getTime()) / 86400000; } /** * 比较两个日期的年差 */ public static int yearDiff(String before, String after) { Date beforeDay = stringtoDate(before, LONG_DATE_FORMAT); Date afterDay = stringtoDate(after, LONG_DATE_FORMAT); return getYear(afterDay) - getYear(beforeDay); } /** * 比较指定日期与当前日期的差 */ public static int yearDiffCurr(String after) { Date beforeDay = new Date(); Date afterDay = stringtoDate(after, LONG_DATE_FORMAT); return getYear(beforeDay) - getYear(afterDay); } /** * 比较指定日期与当前日期的差 */ public static long dayDiffCurr(String before) { Date currDate = DateUtil.stringtoDate(currDay(), LONG_DATE_FORMAT); Date beforeDate = stringtoDate(before, LONG_DATE_FORMAT); return (currDate.getTime() - beforeDate.getTime()) / 86400000; } /** * 获取每月的第一周 */ public static int getFirstWeekdayOfMonth(int year, int month) { Calendar c = Calendar.getInstance(); c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天 c.set(year, month - 1, 1); return c.get(Calendar.DAY_OF_WEEK); } /** * 获取每月的最后一周 */ public static int getLastWeekdayOfMonth(int year, int month) { Calendar c = Calendar.getInstance(); c.setFirstDayOfWeek(Calendar.SATURDAY); // 星期天为第一天 c.set(year, month - 1, getDaysOfMonth(year, month)); return c.get(Calendar.DAY_OF_WEEK); } /** * 获得当前日期字符串,格式"yyyy_MM_dd_HH_mm_ss" * * @return */ public static String getCurrent() { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); StringBuffer sb = new StringBuffer(); sb.append(year).append("_").append(StringUtil.addzero(month, 2)) .append("_").append(StringUtil.addzero(day, 2)).append("_") .append(StringUtil.addzero(hour, 2)).append("_").append( StringUtil.addzero(minute, 2)).append("_").append( StringUtil.addzero(second, 2)); return sb.toString(); } /** * 获得当前日期字符串,格式"yyyy-MM-dd HH:mm:ss" * * @return */ public static String getNow() { Calendar today = Calendar.getInstance(); return dateToString(today.getTime(), FORMAT_ONE); } /** * 判断日期是否有效,包括闰年的情况 * * @param date * YYYY-mm-dd * @return */ public static boolean isDate(String date) { StringBuffer reg = new StringBuffer( "^((\\d{2}(([02468][048])|([13579][26]))-?((((0?"); reg.append("[13578])|(1[02]))-?((0?[1-9])|([1-2][0-9])|(3[01])))"); reg.append("|(((0?[469])|(11))-?((0?[1-9])|([1-2][0-9])|(30)))|"); reg.append("(0?2-?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12"); reg.append("35679])|([13579][01345789]))-?((((0?[13578])|(1[02]))"); reg.append("-?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))"); reg.append("-?((0?[1-9])|([1-2][0-9])|(30)))|(0?2-?((0?["); reg.append("1-9])|(1[0-9])|(2[0-8]))))))"); Pattern p = Pattern.compile(reg.toString()); return p.matcher(date).matches(); }
 
  • 对我有用[13]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
  • afgasdg用户头像
  • afgasdg
  • (米林)
  • 等 级:
#7楼 得分:0回复于:2011-03-31 23:37:13
java dos输入输出
Java code
import java.util.*;public class DaoXu { /** * @param args */ public static void main(String[] args) { // TODO 自动生成方法存根 System.out.println("请输入单个字符并回车: "); Scanner c = new Scanner(System.in); String[] ch = new String[5]; for(int i=0; i<5; i++){ ch[i] = c.next(); } //Arrays.sort(ch); System.out.print("倒序输出: "); for (int j = ch.length-1; j >= 0; j--) { System.out.print(ch[j]+" "); } }}
 

 

 

#8楼 得分:0回复于:2011-03-31 23:38:04
java获取ip地址
Java code
import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.net.InetAddress;import java.net.UnknownHostException;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextField;public class ip extends JFrame implements ActionListener{ private static final long serialVersionUID = 3339481369781127417L; JButton jb1; JButton jb2; JButton jb3; JPanel jp; JLabel jl; JLabel jl1; JTextField jt; public ip() { this.jp = new JPanel(); this.jl = new JLabel(); this.jl1 = new JLabel("您的域名:"); this.jb1 = new JButton("提交"); this.jb2 = new JButton("重置"); this.jb3 = new JButton("退出"); this.jt = new JTextField(20); this.jb1.addActionListener(this); this.jb2.addActionListener(this); this.jb3.addActionListener(this); this.jp.setLayout(new GridLayout(3, 2)); this.jp.add(this.jl1); this.jp.add(this.jt); this.jp.add(this.jb1); this.jp.add(this.jl); this.jp.add(this.jb2); this.jp.add(this.jb3); setBounds(200, 200, 500, 240); add(this.jp); setVisible(true); setDefaultCloseOperation(3); } public static void main(String[] args) { new ip(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == this.jb1) { String url = this.jt.getText(); InetAddress ip = null; try { ip = InetAddress.getByName(url); } catch (UnknownHostException e1) { e1.printStackTrace(); } this.jl.setText(ip.toString()); } else if (e.getSource() == this.jb2) { this.jl.setText(""); this.jt.setText(""); } else { System.exit(0); } }}
 
  • 对我有用[7]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
  • jhw2011用户头像
  • jhw2011
  • (jhw2011)
  • 等 级:
#9楼 得分:0回复于:2011-03-31 23:44:37
感谢楼主!!!
 
  • 对我有用[2]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP

 

#10楼 得分:0回复于:2011-03-31 23:44:53
java系统托盘的应用
Java code
package com.msg; import java.applet.Applet; import java.applet.AudioClip; import java.awt.AWTException; import java.awt.Image; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.SystemTray; import java.awt.TextArea; import java.awt.TrayIcon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import org.jvnet.substance.skin.SubstanceBusinessBlueSteelLookAndFeel; /** * * 创建闪动的托盘图像 * @author Everest * */ public class BickerTray extends JFrame implements Runnable { private static final long serialVersionUID = -3115128552716619277L; private SystemTray sysTray;// 当前操作系统的托盘对象 private TrayIcon trayIcon;// 当前对象的托盘 private ImageIcon icon = null; private TextArea ta = null; private static int count = 1; //记录消息闪动的次数 private boolean flag = false; //是否有新消息 private static int times = 1; //接收消息次数 public BickerTray() { this.createTrayIcon();// 创建托盘对象 Image image = this.getToolkit().getImage(getRes("com/img/f32.gif")); this.setIconImage(image); init(); } public URL getRes(String str){ return this.getClass().getClassLoader().getResource(str); } /** * 初始化窗体的方法 */ public void init() { this.setTitle("消息盒子"); ta = new TextArea(""); ta.setEditable(false); this.add(ta); this.setSize(400, 400); //this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); // 添加窗口最小化事件,将托盘添加到操作系统的托盘 /*this.addWindowListener(new WindowAdapter() { public void windowIconified(WindowEvent e) { addTrayIcon(); } });*/ addTrayIcon(); this.setVisible(true); } /** * 添加托盘的方法 */ public void addTrayIcon() { try { sysTray.add(trayIcon);// 将托盘添加到操作系统的托盘 setVisible(false); // 使得当前的窗口隐藏 new Thread(this).start(); } catch (AWTException e1) { e1.printStackTrace(); } } /** * 创建系统托盘的对象 步骤: * 1,获得当前操作系统的托盘对象 * 2,创建弹出菜单popupMenu * 3,创建托盘图标icon * 4,创建系统的托盘对象trayIcon */ public void createTrayIcon() { sysTray = SystemTray.getSystemTray();// 获得当前操作系统的托盘对象 icon = new ImageIcon(getRes("com/img/f17.gif"));// 托盘图标 PopupMenu popupMenu = new PopupMenu();// 弹出菜单 MenuItem mi = new MenuItem("打开"); MenuItem exit = new MenuItem("退出"); popupMenu.add(mi); popupMenu.add(exit); // 为弹出菜单项添加事件 mi.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ta.setText(ta.getText()+"\n==============================================\n 《通知》 今天下午4:00到大礼堂开会。 \n 第"+times+"次接收时间:"+ new Date().toLocaleString()); // 设置通知消息内容 BickerTray.this.setExtendedState(JFrame.NORMAL); BickerTray.this.setVisible(true); // 显示窗口 BickerTray.this.toFront(); //显示窗口到最前端 flag = false; //消息打开了 count = 0; times++; } }); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); trayIcon = new TrayIcon(icon.getImage(), "消息盒子", popupMenu); /** 添加鼠标监听器,当鼠标在托盘图标上双击时,默认显示窗口 */ trayIcon.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { // 鼠标双击 ta.setText(ta.getText()+"\n==============================================\n 《通知》 今天下午4:00到大礼堂开会。 \n 第"+times+"次接收时间:"+ new Date().toLocaleString()); // 设置通知消息内容 BickerTray.this.setExtendedState(JFrame.NORMAL); BickerTray.this.setVisible(true); // 显示窗口 BickerTray.this.toFront(); flag = false; //消息打开了 count = 0; times++; } } }); } /** * 线程控制闪动 */ public void run() { while (true) { if(flag){ // 有新消息 try { if(count == 1){ // 播放消息提示音 //AudioPlayer p = new AudioPlayer(getRes("file:com/sound/Msg.wav")); //p.play(); p.stop(); try { AudioClip p = Applet.newAudioClip(new URL("file:sound/msg.wav")); p.play(); } catch (MalformedURLException e) { e.printStackTrace(); } } // 闪动消息的空白时间 this.trayIcon.setImage(new ImageIcon("").getImage()); Thread.sleep(500); // 闪动消息的提示图片 this.trayIcon.setImage(icon.getImage()); Thread.sleep(500); } catch (Exception e) { e.printStackTrace(); } count++; }else{ // 无消息或是消息已经打开过 this.trayIcon.setImage(icon.getImage()); try { Thread.sleep(20000); flag = true; } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * @param args */ public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel(new SubstanceBusinessBlueSteelLookAndFeel()); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { public void run() { new BickerTray(); } }); } }
 

 

  • afgasdg用户头像
  • afgasdg
  • (米林)
  • 等 级:
 
//窗口居中显示的方法
 this.setLocationRelativeTo(null);
 public void setLocationRelativeTo(Component c)
设置窗口相对于指定组件的位置。 
如果组件当前未显示,或者 c 为 null,则此窗口将置于屏幕的中央。中点可以使用 GraphicsEnvironment.getCenterPoint 确定。 

如果该组件的底部在屏幕外,则将该窗口放置在 Component 最接近窗口中心的一侧。因此,如果 Component 在屏幕的右部,则 Window 将被放置在左部,反之亦然。
 
  • 对我有用[2]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP

 

#13楼 得分:0回复于:2011-03-31 23:52:18
点到线段的最短距离
Java code
private double pointToLine(int x1, int y1, int x2, int y2, int x0, int y0) { double space = 0; double a, b, c; a = lineSpace(x1, y1, x2, y2);// 线段的长度 b = lineSpace(x1, y1, x0, y0);// (x1,y1)到点的距离 c = lineSpace(x2, y2, x0, y0);// (x2,y2)到点的距离 if (c <= 0.000001 || b <= 0.000001) { space = 0; return space; } if (a <= 0.000001) { space = b; return space; } if (c * c >= a * a + b * b) { space = b; return space; } if (b * b >= a * a + c * c) { space = c; return space; } double p = (a + b + c) / 2;// 半周长 double s = Math.sqrt(p * (p - a) * (p - b) * (p - c));// 海伦公式求面积 space = 2 * s / a;// 返回点到线的距离(利用三角形面积公式求高) return space; } // 计算两点之间的距离 private double lineSpace(int x1, int y1, int x2, int y2) { double lineLength = 0; lineLength = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); return lineLength; }

 

 

  • afgasdg用户头像
  • afgasdg
  • (米林)
  • 等 级:
#17楼 得分:0回复于:2011-03-31 23:57:28
遗传算法
Java code
import java.util.*;public class Tsp { private String cityName[]={"北京","上海","天津","重庆","哈尔滨","长春","沈阳","呼和浩特","石家庄","太原","济南","郑州","西安","兰州","银川","西宁","乌鲁木齐","合肥","南京","杭州","长沙","南昌","武汉","成都","贵州","福建","台北","广州","海口","南宁","昆明","拉萨","香港","澳门"}; //private String cityEnd[]=new String[34]; private int cityNum=cityName.length; //城市个数 private int popSize = 50; //种群数量 private int maxgens = 20000; //迭代次数 private double pxover = 0.8; //交叉概率 private double pmultation = 0.05; //变异概率 private long[][] distance = new long[cityNum][cityNum]; private int range = 2000; //用于判断何时停止的数组区间 private class genotype { int city[] = new int[cityNum]; //单个基因的城市序列 long fitness; //该基因的适应度 double selectP; //选择概率 double exceptp; //期望概率 int isSelected; //是否被选择 } private genotype[] citys = new genotype[popSize]; /** * 构造函数,初始化种群 */ public Tsp() { for (int i = 0; i < popSize; i++) { citys[i] = new genotype(); int[] num = new int[cityNum]; for (int j = 0; j < cityNum; j++) num[j] = j; int temp = cityNum; for (int j = 0; j < cityNum; j++) { int r = (int) (Math.random() * temp); citys[i].city[j] = num[r]; num[r] = num[temp - 1]; temp--; } citys[i].fitness = 0; citys[i].selectP = 0; citys[i].exceptp = 0; citys[i].isSelected = 0; } initDistance(); } /** * 计算每个种群每个基因个体的适应度,选择概率,期望概率,和是否被选择。 */ public void CalAll(){ for( int i = 0; i< popSize; i++){ citys[i].fitness = 0; citys[i].selectP = 0; citys[i].exceptp = 0; citys[i].isSelected = 0; } CalFitness(); CalSelectP(); CalExceptP(); CalIsSelected(); } /** * 填充,将多选的填充到未选的个体当中 */ public void pad(){ int best = 0; int bad = 0; while(true){ while(citys[best].isSelected <= 1 && best<popSize-1) best ++; while(citys[bad].isSelected != 0 && bad<popSize-1) bad ++; for(int i = 0; i< cityNum; i++) citys[bad].city[i] = citys[best].city[i]; citys[best].isSelected --; citys[bad].isSelected ++; bad ++; if(best == popSize ||bad == popSize) break; } } /** * 交叉主体函数 */ public void crossover() { int x; int y; int pop = (int)(popSize* pxover /2); while(pop>0){ x = (int)(Math.random()*popSize); y = (int)(Math.random()*popSize); executeCrossover(x,y);//x y 两个体执行交叉 pop--; } } /** * 执行交叉函数 * @param 个体x * @param 个体y * 对个体x和个体y执行佳点集的交叉,从而产生下一代城市序列 */ private void executeCrossover(int x,int y){ int dimension = 0; for( int i = 0 ;i < cityNum; i++) if(citys[x].city[i] != citys[y].city[i]){ dimension ++; } int diffItem = 0; double[] diff = new double[dimension]; for( int i = 0 ;i < cityNum; i++){ if(citys[x].city[i] != citys[y].city[i]){ diff[diffItem] = citys[x].city[i]; citys[x].city[i] = -1; citys[y].city[i] = -1; diffItem ++; } } Arrays.sort(diff); double[] temp = new double[dimension]; temp = gp(x, dimension); for( int k = 0; k< dimension;k++) for( int j = 0; j< dimension; j++) if(temp[j] == k){ double item = temp[k]; temp[k] = temp[j]; temp[j] = item; item = diff[k]; diff[k] = diff[j]; diff[j] = item; } int tempDimension = dimension; int tempi = 0; while(tempDimension> 0 ){ if(citys[x].city[tempi] == -1){ citys[x].city[tempi] = (int)diff[dimension - tempDimension]; tempDimension --; } tempi ++; } Arrays.sort(diff); temp = gp(y, dimension); for( int k = 0; k< dimension;k++) for( int j = 0; j< dimension; j++) if(temp[j] == k){ double item = temp[k]; temp[k] = temp[j]; temp[j] = item; item = diff[k]; diff[k] = diff[j]; diff[j] = item; } tempDimension = dimension; tempi = 0; while(tempDimension> 0 ){ if(citys[y].city[tempi] == -1){ citys[y].city[tempi] = (int)diff[dimension - tempDimension]; tempDimension --; } tempi ++; } } /** * @param individual 个体 * @param dimension 维数 * @return 佳点集 (用于交叉函数的交叉点) 在executeCrossover()函数中使用 */ private double[] gp(int individual, int dimension){ double[] temp = new double[dimension]; double[] temp1 = new double[dimension]; int p = 2 * dimension + 3; while(!isSushu(p)) p++; for( int i = 0; i< dimension; i++){ temp[i] = 2*Math.cos(2*Math.PI*(i+1)/p) * (individual+1); temp[i] = temp[i] - (int)temp[i]; if( temp [i]< 0) temp[i] = 1+temp[i]; } for( int i = 0; i< dimension; i++) temp1[i] = temp[i]; Arrays.sort(temp1); //排序 for( int i = 0; i< dimension; i++) for( int j = 0; j< dimension; j++) if(temp[j]==temp1[i]) temp[j] = i; return temp; } /** * 变异 */ public void mutate(){ double random; int temp; int temp1; int temp2; for( int i = 0 ; i< popSize; i++){ random = Math.random(); if(random<=pmultation){ temp1 = (int)(Math.random() * (cityNum)); temp2 = (int)(Math.random() * (cityNum)); temp = citys[i].city[temp1]; citys[i].city[temp1] = citys[i].city[temp2]; citys[i].city[temp2] = temp; } } } /** * 打印当前代数的所有城市序列,以及其相关的参数 */ public void print(){ /** * 初始化各城市之间的距离 */ private void initDistance(){ for (int i = 0; i < cityNum; i++) { for (int j = 0; j < cityNum; j++){ distance[i][j] = Math.abs(i-j); } } } /** * 计算所有城市序列的适应度 */ private void CalFitness() { for (int i = 0; i < popSize; i++) { for (int j = 0; j < cityNum - 1; j++) citys[i].fitness += distance[citys[i].city[j]][citys[i].city[j + 1]]; citys[i].fitness += distance[citys[i].city[0]][citys[i].city[cityNum - 1]]; } } /** * 计算选择概率 */ private void CalSelectP(){ long sum = 0; for( int i = 0; i< popSize; i++) sum += citys[i].fitness; for( int i = 0; i< popSize; i++) citys[i].selectP = (double)citys[i].fitness/sum; } /** * 计算期望概率 */ private void CalExceptP(){ for( int i = 0; i< popSize; i++) citys[i].exceptp = (double)citys[i].selectP * popSize; } /** * 计算该城市序列是否较优,较优则被选择,进入下一代 */ private void CalIsSelected(){ int needSelecte = popSize; for( int i = 0; i< popSize; i++) if( citys[i].exceptp<1){ citys[i].isSelected++; needSelecte --; } double[] temp = new double[popSize]; for (int i = 0; i < popSize; i++) {// temp[i] = citys[i].exceptp - (int) citys[i].exceptp;// temp[i] *= 10; temp[i] = citys[i].exceptp*10; } int j = 0; while (needSelecte != 0) { for (int i = 0; i < popSize; i++) { if ((int) temp[i] == j) { citys[i].isSelected++; needSelecte--; if (needSelecte == 0) break; } } j++; } } /** * @param x * @return 判断一个数是否是素数的函数 */ private boolean isSushu( int x){ if(x<2) return false; for(int i=2;i<=x/2;i++) if(x%i==0&&x!=2) return false; return true; } /** * @param x 数组 * @return x数组的值是否全部相等,相等则表示x.length代的最优结果相同,则算法结束 */ private boolean isSame(long[] x){ for( int i = 0; i< x.length -1; i++) if(x[i] !=x[i+1]) return false; return true; } /** * 打印任意代最优的路径序列 */ private void printBestRoute(){ CalAll(); long temp = citys[0].fitness; int index = 0; for (int i = 1; i < popSize; i++) { if(citys[i].fitness<temp){ temp = citys[i].fitness; index = i; } } System.out.println(); System.out.println("最佳路径的序列:"); for (int j = 0; j < cityNum; j++) { String cityEnd[]={cityName[citys[index].city[j]]}; for(int m=0;m<cityEnd.length;m++) { System.out.print(cityEnd[m] + " "); } } //System.out.print(citys[index].city[j] + cityName[citys[index].city[j]] + " "); //System.out.print(cityName[citys[index].city[j]]); System.out.println(); } /** * 算法执行 */ public void run(){ long[] result = new long[range]; //result初始化为所有的数字都不相等 for( int i = 0; i< range; i++) result[i] = i; int index = 0; //数组中的位置 int num = 1; //第num代 while(maxgens>0){ System.out.println("----------------- 第 "+num+" 代 -------------------------"); CalAll(); print(); pad(); crossover(); mutate(); maxgens --; long temp = citys[0].fitness; for ( int i = 1; i< popSize; i++) if(citys[i].fitness<temp){ temp = citys[i].fitness; } System.out.println("最优的解:"+temp); result[index] = temp; if(isSame(result)) break; index++; if(index==range) index = 0; num++; } printBestRoute(); } /** * @param a 开始时间 * @param b 结束时间 */ public void CalTime(Calendar a,Calendar b){ long x = b.getTimeInMillis() - a.getTimeInMillis(); long y = x/1000; x = x - 1000*y; System.out.println("算法执行时间:"+y+"."+x+""); } /** * 程序入口 */ public static void main(String[] args) { Calendar a = Calendar.getInstance(); //开始时间 Tsp tsp = new Tsp(); tsp.run(); Calendar b = Calendar.getInstance(); //结束时间 tsp.CalTime(a, b); }}
 
  • 对我有用[6]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP
  • jhw2011用户头像
  • jhw2011
  • (jhw2011)
  • 等 级:
#18楼 得分:0回复于:2011-03-31 23:58:57
挺不错的啊
 
  • 对我有用[1]
  • 丢个板砖[0]
  • 引用
  • 举报
  • 管理
  • TOP

 

 
java 字符串解析
Java code
StringTokenizer tokenizer = new StringTokenizer(number, ","); boolean bool = true; while (tokenizer.hasMoreTokens()) { try { Double.valueOf(tokenizer.nextToken()); } catch (Exception e) { bool = false; } }//将字符串转化为数组的方法int gv[]; int i = 0; StringTokenizer tokenizer = new StringTokenizer(goodsVolume, ",, "); gv = new int[tokenizer.countTokens()];//动态的决定数组的长度 while (tokenizer.hasMoreTokens()) { String d = tokenizer.nextToken(); gv[i] = Integer.valueOf(d);//将字符串转换为整型 i++; } //字符串解析 private String[] stringAnalytical(String str, String divisionChar) { String string[]; int i = 0; StringTokenizer tokenizer = new StringTokenizer(str, divisionChar); string = new String[tokenizer.countTokens()];// 动态的决定数组的长度 while (tokenizer.hasMoreTokens()) { string[i] = new String(); string[i] = tokenizer.nextToken(); i++; } return string;// 返回字符串数组 } int countTokens() 计算在生成异常之前可以调用此 tokenizer 的 nextToken 方法的次数。 boolean hasMoreElements() 返回与 hasMoreTokens 方法相同的值。 boolean hasMoreTokens() 测试此 tokenizer 的字符串中是否还有更多的可用标记。 Object nextElement() 除了其声明返回值是 Object 而不是 String 之外,它返回与 nextToken 方法相同的值。 String nextToken() 返回此 string tokenizer 的下一个标记。 String nextToken(String delim) 返回此 string tokenizer 的字符串中的下一个标记。 public class StringAnalytical { // 字符串解析,将字符串转根据分割符换成字符串数组 private String[] stringAnalytical(String string, char c) { int i = 0; int count = 0; if (string.indexOf(c) == -1) return new String[] { string };// 如果不含分割符则返回字符本身 char[] cs = string.toCharArray(); int length = cs.length; for (i = 1; i < length - 1; i++) {// 过滤掉第一个和最后一个是分隔符的情况 if (cs[i] == c) { count++;// 得到分隔符的个数 } } String[] strArray = new String[count + 1]; int k = 0, j = 0; String str = string; if ((k = str.indexOf(c)) == 0)// 去掉第一个字符是分隔符的情况 str = str.substring(k + 1); if (str.indexOf(c) == -1)// 检测是否含分隔符,如果不含则返回字符串 return new String[] { str }; while ((k = str.indexOf(c)) != -1) {// 字符串含分割符的时候 strArray[j++] = str.substring(0, k); str = str.substring(k + 1); if ((k = str.indexOf(c)) == -1 && str.length() > 0) strArray[j++] = str.substring(0); } return strArray; } public void printString(String[] s) { System.out.println("*********************************"); for (String str : s) System.out.println(str); } public static void main(String[] args) { String[] str = null; StringAnalytical string = new StringAnalytical(); str = string.stringAnalytical("1aaa", '@'); string.printString(str); str = string.stringAnalytical("2aaa@", '@'); string.printString(str); str = string.stringAnalytical("@3aaa", '@'); string.printString(str); str = string.stringAnalytical("4aaa@bbb", '@'); string.printString(str); str = string.stringAnalytical("@5aaa@bbb", '@'); string.printString(str); str = string.stringAnalytical("6aaa@bbb@", '@'); string.printString(str); str = string.stringAnalytical("@7aaa@", '@'); string.printString(str); str = string.stringAnalytical("@8aaa@bbb@", '@'); string.printString(str); str = string.stringAnalytical("@9aaa@bbb@ccc", '@'); string.printString(str); str = string.stringAnalytical("@10aaa@bbb@ccc@eee", '@'); string.printString(str); }}