Java笔记
4、Applet中使用JFrame
Applet中不能直接添加JFrame,但是可以创建JFrame对象并显示,需要注意的是:不能设置-setDefaultCloseOperation(JFrame.Exit_ON_CLOSE);因为JFrame不能关闭Applet,Applet的生命周期由浏览器管理。
3、使用Google TTS播放语音
支持库:jl1.0.1.jar,用于声音播放
public void test(){
try { URL url = new URL("http://translate.google.com/translate_tts?q=2008年5月12日14点28分,四川汶川发生8.0级地震&tl=zh"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3 (LEXLOO) "); final InputStream is = connection.getInputStream(); final Player player = new Player(is); EventQueue.invokeLater(new Runnable() { @Override public void run() { try { player.play(); is.close(); } catch (Exception ex) { ex.printStackTrace(); } } }); } catch (Exception ex) { ex.printStackTrace(); }
}
2、让Java程序只运行一个实例
在程序开始的时候执行 new SingleInstance(),就不会打开第二个实例。端口可以修改。
public class SingleInstance { private volatile boolean blocking = true; public SingleInstance() { new Checker(); while (blocking) { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } private class Checker implements Runnable { private Thread thread = new Thread(this); private Checker() { thread.start(); } @Override public void run() { try { Socket sock = new Socket("127.0.0.1", 17909); System.out.println("程序已经在运行"); System.exit(0); } catch (Exception e) { } try { ServerSocket server = new ServerSocket(17909); blocking = false; while (true) { server.accept(); } } catch (Exception e) { } } } }
1、获取本机的Mac地址(JDK6)
当前正好需要这个功能,在网上简单搜了下,都是通过os的方法,其实JDK6已经支持。修改下面代码也可以通过IP地址查找Mac地址。
/** * 获取本机Mac地址 * * @return mac地址 */ private static String getMacAddress() { try { NetworkInterface ne = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); byte[] macBytes = ne.getHardwareAddress(); StringBuilder sb = new StringBuilder(); for (byte b : macBytes) { sb.append(String.format("%02X", b)); sb.append("-"); } sb.deleteCharAt(sb.length() - 1); return sb.toString(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } return ""; }