Java 透明和不规则 Swing 窗口

SWT行 AWT/Swing也行系列 1 -实现半透明及不规则窗体 阅读详情

历史

本机应用程序的开发人员通常在开发 UI 应用程序中享受了更高级的灵活性。但是为此而付出的代价是将应用程序限制在某一特定平台上,在许多情况中,这种灵活性不如获得更为丰富的 UI 体验和桌面紧密集成那么重要。从传统上讲,跨平台 UI 工具箱,例如 Swing、SWT、QT 和 wxWidgets 趋向于被动应付众所周知的两难问题。当只有某些目标平台支持所要求的功能时怎么办?在这种情况下,模拟缺失的功能可能只会让您南辕北辙。

不规则和透明窗口是跨平台 UI 工具箱局限性的最好例子。如果在特定目标平台不支持此项功能,那么在该平台上就没有什么更多事情要做了,此项功能可能用作强有力的参数向工具箱添加该项功能。但是,Swing 开发人员社区长久以来一直争论主要目标平台不久就会提供这些功能。事实上,Windows 自从 Windows 95 ( 参见 MSDN 上的 SetWindowRgn 文档 )就已经支持不规则窗口了。在 X11 中匹配功能自从 1989 年 ( 参见 X Nonrectangular Window Shape Extension Library PDF 文档 )就已经可用了。在 OS X 中您仅能在 JFrame 上设置透明的背景颜色。

直到现在,对跨平台透明和不规则窗口有兴趣的 Swing 应用程序有三种主要可选方式。

第一种方法的主要问题是要使用 Robot 类。即使您有权限获得屏幕截图,您也必须在显示窗口之前完成。此外,如何保持桌面后台同步?假设在后台正在播放 YouTube 视频。与窗口生成的事件不同( 调整大小,移动 ),AWT 并不在任何交叉窗口的重画上提供注册侦听器的任何方式。虽然 Chris 和 Joshua 通过在至少每秒内进行快照提供解决方法,这对于覆盖后台视频播放还不够。而且在每次快照前需要对窗口加以隐藏;这可能导致可见的闪烁。

使用 JNI 和 JNA 导致显著的视觉保真性改进。纯 JNI 会带来开销的急剧下降:您必须将目标平台的每一个相关的 API 绑定,还要捆绑本机库。JNA 为您分担这项重任; 它捆绑主机库并提供能在运行时提取并加载它们的类加载器。它支持 Linux、 OS X、 Windows、 Solaris 和 FreeBSD。

Consumer JRE

Java SE 6 Update N, 通常称作 Consumer JRE, 是 Sun 公司的努力成果,为重新配置 Java 将其作为开发富桌面应用程序的可行方法。在 Consumer JRE 中的新功能和主要改进列表相当广泛,并将特别闪耀的宝石隐藏在最新一周构建代码之一的发行说明中。Bug 6633275 被简单地赋予“需要支持不规则/透明窗口”的标题。但是该实现核心 JDK 新功能的可能性所带给 Swing 开发人员的意义是深远的。本文的剩余部分将显示能够实现和如何实现该功能的几个示例。

在进一步研究之前,有一个非常重要的注意事项。由于 Consumer JRE 被官方认为是对稳定 JDK 发行的一个次要更新,因此在“公共”包中不能添加任何新的 API( 类、方法等等 ),例如 java.awt 或 javax.swing。在本文中讨论的所有 API 在新 com.sun.awt.AWTUtilities 类中出现,该类不是官方支持的部分 API。它在 Java SE 7 中的位置最有可能发生改变,签名方法可能在现在和最终的 Consumer JRE 发行之间发生轻微变化。所以当这种改变发生时准备更改您自己的代码。

AWTUtilities 类

我首先讨论 com.sun.awt.AWTUtilities 类,请参见 在核心 Java 中的透明和不规则窗口 博客条目。首先我们从图 1 中的简单窗口入手:

图 1. 带有控件的窗口

要使窗口透明,您可以使用 AWTUtilities.setWindowOpacity(Window, float) 方法,如图 2 所示:

图 2. 相同的窗口,但是有 50% 的不透明度

要使窗口不规则,您可以使用 AWTUtilities.setWindowShape(Window, Shape) 方法,如图 3 所示:

图 3. 相同的窗口,但是被一个椭圆剪裁

正如您从图 3 中能看到的,不规则的窗口看起来不是很好。窗口的边缘呈锯齿状并且整体印象也不是很干净。要获得不规则窗口的更佳视觉效果,您必须使用 AWTUtilities.setWindowOpaque(Window, boolean) API,并使用柔性裁剪绘画窗口背景。这在后续的 Swing 窗口的柔性裁剪和每像素透明度 博客条目中进行了阐明。对于窗口的左上角和右上角,该条目采用 Chris Campbell 的 柔性裁剪教程 以及 Romain Guy 的 反射教程, 其中包括 Sebastien Petrucci 的改进。图 4 显示了每个像素透明的柔性裁剪窗口:

图 4. 柔性裁剪和每个像素透明的窗口

现在我们手头上已经有了这些 API,我们打算做些什么呢?对它们进行探索这种可能性当然是另人好奇的,我们正打算看看几个多样混合的示例。

工具提示

让我们使应用工具提示变得透明怎么样?对于轻量级工具提示,实现这一目标是相当容易的,因为它们被作为 Swing 顶级窗口的一部分加以绘画。( 要获得关于轻量级弹出菜单的详细信息,请参见 玻璃窗格和轻量级弹出菜单 条目。)但是,一旦工具提示成为重量级并“打破”窗口绑定,您必须继续采用 Robot 或 JNI/JNA。现在让我们看一看使用 AWTUtilities API 如何完成这项任务。

javax.swing.PopupFactory 是创建弹出菜单的厂。工具提示只是弹出功能的一个例子;其他例子包括组合框下拉列表和菜单。PopupFactory.setSharedInstance API 可以被用于设置自定义弹出厂,这就是我们想要做的。当前的弹出厂被用于创建所有应用弹出窗口,我们将在所有的工具提示上安装自定义不透明厂。

核心弹出厂的实现是相当复杂的。首先尝试创建轻量级弹出窗口,当要求创建重量级窗口时,系统要管理高速缓存以便重用先前创建的弹出窗口。实现过程将创建一个新的重量级弹出窗口;在相对较新的膝上型电脑上运行不同的方案还未显示任何突出的性能突破。让我们从自定义弹出厂着手研究:


public class TranslucentPopupFactory extends PopupFactory {
@Override
public Popup getPopup(Component owner, Component contents, int x, int y)
throws IllegalArgumentException {
// A more complete implementation would cache and reuse
// popups
return new TranslucentPopup(owner, contents, x, y);
}
}

TranslucentPopup 的实现相当简单。构造器创建新的 JWindow,将工具提示的不透明度设置为 0.8,从 Looks 项目安装提供拖放阴影的自定义边框:


TranslucentPopup(Component owner, Component contents, int ownerX, int ownerY) {
// create a new heavyweight window
this.popupWindow = new JWindow();
// mark the popup with partial opacity
com.sun.awt.AWTUtilities.setWindowOpacity(popupWindow,
(contents instanceof JToolTip) ? 0.8f : 0.95f);
// determine the popup location
popupWindow.setLocation(ownerX, ownerY);
// add the contents to the popup
popupWindow.getContentPane().add(contents, BorderLayout.CENTER);
contents.invalidate();
JComponent parent = (JComponent) contents.getParent();
// set the shadow border
parent.setBorder(new ShadowPopupBorder());
}

现在我们需要重写 Popup 的 show() 方法来标记整个弹出窗口为透明样式。这要求拖放阴影边框的每个像素具有透明性。


@Override
public void show() {
this.popupWindow.setVisible(true);
this.popupWindow.pack();
// mark the window as non-opaque, so that the
// shadow border pixels take on the per-pixel
// translucency
com.sun.awt.AWTUtilities.setWindowOpaque(this.popupWindow, false);
}

hide() 方法只是隐藏并处置弹出窗口:


@Override
public void hide() {
this.popupWindow.setVisible(false);
this.popupWindow.removeAll();
this.popupWindow.dispose();
}

要安装该弹出窗口,仅简单调用


PopupFactory.setSharedInstance(new TranslucentPopupFactory());

图 5 显示了一个具有透明工具提示的示例帧。注意,与工具提示保持视觉(透明性和拖放阴影边框)上的一致性跨越 Swing 帧绑定并扩展到后台 Eclipse 窗口。

图 5. 工具提示

现在我们做相同的动画。当工具提示显示时将颜色调淡些,当它被隐藏起来时把它的颜色渐隐如何?一旦您熟悉了 AWTUtilities API,上述操作不难实现。下面给出 show() 方法的代码:


@Override
public void show() {
if (this.toFade) {
// mark the popup with 0% opacity
this.currOpacity = 0;
com.sun.awt.AWTUtilities.setWindowOpacity(popupWindow, 0.0f);
}

this.popupWindow.setVisible(true);
this.popupWindow.pack();

// mark the window as non-opaque, so that the
// shadow border pixels take on the per-pixel
// translucency
com.sun.awt.AWTUtilities.setWindowOpaque(this.popupWindow, false);

if (this.toFade) {
// start fading in
this.fadeInTimer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
currOpacity += 20;
if (currOpacity <= 100) {
com.sun.awt.AWTUtilities.setWindowOpacity(popupWindow,
currOpacity / 100.0f);
// workaround bug 6670649 - should call
// popupWindow.repaint() but that will not repaint the
// panel
popupWindow.getContentPane().repaint();
} else {
currOpacity = 100;
fadeInTimer.stop();
}
}
});
this.fadeInTimer.setRepeats(true);
this.fadeInTimer.start();
}
}

这时我们用 0% 的不透明度标记弹出窗口。然后我们启动重复计时器进行五次迭代。每一次跌代我们增加窗口不透明度 20% 并重新绘画。最后我们停止计时器。最终的视觉结果是工具提示外观的平滑退色序列,这一序列持续大约 250 毫秒。

hide() 方法非常类似:


@Override
public void hide() {
if (this.toFade) {
// cancel fade-in if it's running.
if (this.fadeInTimer.isRunning())
this.fadeInTimer.stop();

// start fading out
this.fadeOutTimer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
currOpacity -= 10;
if (currOpacity >= 0) {
com.sun.awt.AWTUtilities.setWindowOpacity(popupWindow,
currOpacity / 100.0f);
// workaround bug 6670649 - should call
// popupWindow.repaint() but that will not repaint the
// panel
popupWindow.getContentPane().repaint();
} else {
fadeOutTimer.stop();
popupWindow.setVisible(false);
popupWindow.removeAll();
popupWindow.dispose();
currOpacity = 0;
}
}
});
this.fadeOutTimer.setRepeats(true);
this.fadeOutTimer.start();
} else {
popupWindow.setVisible(false);
popupWindow.removeAll();
popupWindow.dispose();
}
}

首先检查退色序列是否仍在运行,根据需要将它删除。然后,不立即隐藏窗口,而是将不透明度以 10% 的增量从 100% 改为 0(因此渐隐序列是退色序列的两倍)然后隐藏并处置弹出窗口。注意两种方法参阅了 Boolean toFade 变量 —— 它在工具提示上被设置为 true。弹出窗口的其他类型(菜单、组合框下拉列表)没有退色动画。

视频反射

现在让我们做些更为激动人心的事情。在 Romain Guy 的博客条目 重画管理器演示(第 11 章) 中,它显示了提供反射功能的 Swing 组件。从他与 Chet Haase 合著的 《 肮脏的富客户机 》 书中抽取一段测试应用程序,其中显示该组件提供了 QuickTime 电影的实时反射。在窗口绑定 之外 进行反射如何?

首先要有实际应用中的反射帧的屏幕截图。图 6 显示了正在播放 “Get a Mac” 广告的形状规则的 Swing 帧( 使用嵌入式 QuickTime 播放器 ), 伴随着覆盖桌面的透明的实时反射:

图 6. QuickTime 电影的反射

该实现重用了来自 Romain 的几个构造块并将它们扩展到“桢外”。它还有一个重画管理器 ( 要了解关于重画管理器方面的详细信息,请参见 使用重画管理器的验证覆盖 条目 )以便将主桢内容与反射窗口保持同步。还需要在主桢上注册组件侦听器和窗口侦听器以便确保反射窗口与主窗口的可见性、位置和大小保持同步。除此之外,还要有一个自定义窗格将其内容绘画到脱屏缓冲区。脱屏缓冲区被用于绘画主桢和在反射窗口内的反射。

让我们看一下代码。主类是扩展 JFrame 的 JReflectionFrame。构造器创建了反射窗口并向其中添加非双重缓冲和透明的面板。还重写了面板的 paintComponent() 以便绘画主桢内容的反射。在初始化反射桢的位置和大小后,我们安装了一个自定义重画管理器。


public JReflectionFrame(String title) {
super(title);
reflection = new JWindow();
reflectionPanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
// paint the reflection of the main window
paintReflection(g);
}
};
// mark the panel as non-double buffered and non-opaque
// to make it translucent.
reflectionPanel.setDoubleBuffered(false);
reflectionPanel.setOpaque(false);

reflection.setLayout(new BorderLayout());
reflection.add(reflectionPanel, BorderLayout.CENTER);

// register listeners - see below
...

// initialize the reflection size and location
reflection.setSize(getSize());
reflection.setLocation(getX(), getY() + getHeight());
reflection.setVisible(true);

// install custom repaint manager to force re-painting
// the reflection when something in the main window is
// repainted
RepaintManager.setCurrentManager(new ReflectionRepaintManager());
}

下面是保持反射窗口与主桢同步的侦听器:


this.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
reflection.setVisible(false);
}

@Override
public void componentMoved(ComponentEvent e) {
// update the reflection location
reflection.setLocation(getX(), getY() + getHeight());
}

@Override
public void componentResized(ComponentEvent e) {
// update the reflection size and location
reflection.setSize(getWidth(), getHeight());
reflection.setLocation(getX(), getY() + getHeight());
}

@Override
public void componentShown(ComponentEvent e) {
reflection.setVisible(true);

// if the reflection window is opaque, mark
// it as per-pixel translucent
if (com.sun.awt.AWTUtilities.isWindowOpaque(reflection)) {
com.sun.awt.AWTUtilities.setWindowOpaque(reflection, false);
}
}
});

this.addWindowListener(new WindowAdapter() {
@Override
public void windowActivated(WindowEvent e) {
// force showing the reflection window
reflection.setAlwaysOnTop(true);
reflection.setAlwaysOnTop(false);
}
});

重画管理器相当简单:它强制主桢的整个根窗格重画,然后更新反射窗口。这样可以最优化更新区域反射的同步,对于示例应用程序要达到的目的,这点就足够了。


private class ReflectionRepaintManager extends RepaintManager {
@Override
public void addDirtyRegion(JComponent c, int x, int y, int w, int h) {
Window win = SwingUtilities.getWindowAncestor(c);
if (win instanceof JReflectionFrame) {
// mark the entire root pane to be repainted
JRootPane rp = ((JReflectionFrame) win).getRootPane();
super.addDirtyRegion(rp, 0, 0, rp.getWidth(), rp.getHeight());

// workaround bug 6670649 - should call reflection.repaint()
// but that will not repaint the panel
reflectionPanel.repaint();
} else {
super.addDirtyRegion(c, x, y, w, h);
}
}
}

主桢 (脱屏缓冲区) 和反射窗口的绘图代码在 Romain 的 反射教程 中进行了详细描述。

结束语

对这一结果我们期待已久,现在终于如愿以偿。尽管创建透明和不规则窗口的 API 还没有官方支持的包,但是它们仍可用于创建可视的富跨平台 UI。从 Romain 的博客 透明和不规则窗口( Extreme GUI Makeover ) 条目展示 JNA 项目,用于创建动画的透明不规则窗口的可视化竞争应用。现在您可以使用核心 JDK 做同样的处理。本文全面介绍了显示实际应用中的核心 JDK API 的三个示例。我确信您能想出更多的例子。

参考资料

  • 本文的 示例代码。
  • Swing 绘画流水线的 概述
  • 关于使用 Robot 类来模拟透明窗口的相关 章节, 出自 Joshua Marinacci 和 Chris Adamson 编著的Swing Hacks
  • 由 Timothy Wall 编著的 JNA 项目
  • 在 Consumer JRE 中创建透明和不规则窗口的基本 API 介绍
  • 在 Consumer JRE 中创建每像素透明和柔性裁剪的不规则窗口的 介绍
  • 由 Romain Guy 编写的关于创建透明反射 教程
  • 由 Chris Campbell 编写的关于柔性裁剪 教程
  • 视频反射组件的 概述,出自 Chet Haase 和 Romain Guy 编著的《肮脏的富客户机》。

Kirill Grouchnikov 在读初中时就开始编写软件,获得计算机科学专业的学士学位后,他继续从事这方面的工作。他感兴趣的主要领域包括桌面应用程序、成像算法和高级 UI 技术。

 

java AWTUtilities库 包含java界面设计中com.sun.awt.AWTUtilities ,及组件开发com.corba等开发库 立即下载

相关推荐

JAVA创建不规则窗口

现在JAVA Swing也能写出任意形状的不规则窗口以及半透明窗口程序了,是真正的任意形状及透明窗口,不是屏幕截图然后设为窗口程序背景。附源代码,并加了详细的注释。

com.sun.awt.AWTUtilities的使用

有时候,在Java中我们会设置窗口的透明度,有第三方方法,但JDK包中自带的也有一种方法: 就是导入com.sun.awt.AWTUtilities package com.lovemu.snow; import java.awt.Color; import javax.swing.JFrame; import com.sun.awt.AWTUtilities; p...

网站开发初中级代码参考-转载 1494

Swing实现半透明窗口的Sample

程序项目可以用 NetBeans IDE 打开

com.sun.awt.AWTUtilities被废弃的替代方案

## 问题背景 相信在用`setWindowShape`或者`setWindowOpaque`的朋友在升级了jdk版本后发现用不了了,是因为`com.sun.awt.AWTUtilities`在未来的版本中被废弃了,那如果不想降低jdk版本还想实现对应的功能怎么办呢? ## 解决方案 既然官方敢废弃,说明原来的东西肯定有问题,或者有更好的替代方案,事实上 - `setWindowShape`的替代方案是调用JFrame的`setShape(Shape shape)`就可以了 - `setWindowOpa

Doge的技术小屋 983

【VSCode】【Clangd】从零构建:基于LLVM/Clangd+MINGW+CMake的Windows高性能C/C++开发环境实战

本文详细介绍了如何在Windows平台搭建基于LLVM/Clangd+MINGW+CMake的高性能C/C++开发环境。通过VSCode配置Clangd语言服务器,结合MINGW提供的GCC工具链和CMake的跨平台构建能力,实现轻量级、高效率的开发体验。文章包含从环境准备到实战配置的完整指南,特别适合追求开发效率和跨平台兼容性的开发者。

weixin_28839629的博客 317

[uboot] (第一章)uboot流程——概述

[uboot] uboot流程系列: [project X] tiny210(s5pv210)上电启动流程(BL0-BL2)建议先看《[project X] tiny210(s5pv210)上电启动流程(BL0-BL2)》,根据例子了解一下上电之后的BL0\BL1\BL2阶段,以及各个阶段的运行位置,功能。==============================================

ooonebook的博客 1万+

IDEA使用不了com.sun.awt.AWTUtilities解决

com.sun.awt这个包比较特殊,默认被限制访问,使用它需要单独引入jdk下的rt.jar包,如图,相信添加一个jar包不是什么难事~

Doge的技术小屋 2523

AWD线下攻防赛总结

在本地组策略编辑器里面,依次展开计算机配置—>管理模板—>Windows组件—>远程桌面服务—>远程桌面会话主机—>连接—>限制连接的数量。8.Web目录环境查找相关可疑文件:jpg/png/rar,属性、解压。进程线程:netstat / ps -aux/netstat -apt。4.查看/etc/init.d/rc.local中启动服务有无异常。1.不使用默认口令,修改成复杂的,并确保和web环境连接。5.使用脚本开启进程监控、目录监控、流量监控。文件操作监控.exe/御剑文件监控.exe。

XuJL89的博客 638

com.sun.awt.AWTUtilities.setWindowOpacity相关说明

com.sun.awt.AWTUtilities.setWindowOpacity(Window arg0, float arg1 ); 是JDK6之后增加的一个新 的方法,作用是可以使得窗体以及窗体内部的组件透明。但是在使用的时候可能会遇到如下俩个麻烦:     1.在eclipse中(jdk1.6.*)版本中出现编译不通过而报错,报错是因为这个包里面的方法不属于jdk正式版本,也就...

博学切问 609

YOLOv11的网络结构概览(Backbone-Neck-Head):介绍骨干网络(Backbone)、特征融合层(Neck)和检测头(Head)的作用

YOLOv11架构解析:从特征提取到目标检测 YOLOv11继承了YOLO系列的经典三组件架构,包含Backbone、Neck和Head三部分。Backbone基于改进的CSPDarknet,通过Conv和C3模块进行多尺度特征提取;Neck采用FPN+PAN结构融合不同层次特征;Head负责检测任务输出。网络整体设计注重高效性和多尺度特征融合,采用C3模块优化信息流和梯度流,配合SPPCSPC增强特征表达能力。该架构在保持实时检测速度的同时,提升了目标检测精度,体现了YOLO系列"一次看全图&q

本博客聚焦 YOLOv11 全流程落地,涵盖架构优化、数据集处理、训练技巧与多场景部署,兼及国产数据库、Java 开发与 AI 模型应用,内容兼顾理论与工程实践,为开发者提供系统干货,助力高效提升技术能力。 1万+

第4章--CANoe library开发 - 诊断功能

因为专栏要做的是汽车ECU自动化测试程序,测试的是ECU的诊断和刷新,因此就需要利用CANoe的接口,开发一些方便使用的诊断报文收发函数。

j187067046的博客 1404

JDK 6 u10 中 Swing最新特性:增加透明窗体及不规则窗体功能:com.sun.awt.AWTUtilities

原文地址:http://developers.sun.com.cn/Java/translucent-and-shaped-swing-windows.html透明和不规则 Swing 窗口

3332

60、磁悬浮主动隔振系统的LQR控制研究

本研究针对磁悬浮主动隔振系统,提出了一种结合ANN建模、LQR控制与MPGA优化的综合控制方案。通过建立系统的动力学与状态空间模型,利用混合训练算法的ANN精确描述MSVI的非线性和滞后特性,并设计基于最小力传递率的LQR控制器。为优化LQR的Q和R矩阵,引入多群体遗传算法(MPGA),有效克服传统GA的早熟收敛问题,提升搜索效率与控制性能。仿真结果表明,在单频、扫频、随机及冲击激励下,该方法显著降低传递力幅值,隔振效果远优于被动系统。研究验证了所提方法的有效性,为磁悬浮隔振技术的实际应用奠定了基础,并展望

linux6sysadmin的博客 129

透明和不规则 Swing 窗口

透明和不规则 Swing 窗口  

陈玉国 877

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

swing的不规则与透明窗体

public class ShapedWindow extends JFrame { public ShapedWindow() { super("不规则窗体"); this.setLayout(new FlowLayout()); JButton button = new JButton("退出按钮"); this.add(button); this.add(n...

renjunfu的博客 209

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

java swing 不规则窗体_Swing 透明窗体和不规则窗体

透明窗体实现如下:public class TranslucentWindow extends JFrame {public TranslucentWindow() {super("透明窗体");this.setLayout(new FlowLayout());this.add(new JButton("按钮"));this.add(new JCheckBox("复选按钮"));this.add(...

weixin_39951396的博客 177

黑马程序员JAVA  不规测 半透明 边…

import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsDevice; impor

u012202641的专栏 476

SWT行,AWT/Swing也行系列(1)-实现半透明及不规则窗体

对于Java来说,GUI开发一直都是项比较头疼的事情。从AWT的功能奇缺,到Swing的臃肿不堪,往如梦魇般困扰着Java开发人员。于是,有一群人开始走向了邪路……这群误入岐途的人(至少Sun是这么认为的……),走出了自己的一条路,名为SWT(Standard Widget Toolkit)的不归路(Sun,Sun|||)。说起SWT冒着被诟病为邪恶所换取的,无外以下几点:1.彻底摒弃了AWT/S...

wangxiaohigh 134

Java Swing根据图片创建不规则窗体(二)

本来这篇文章是应该上午就写好的,可是写到一半,公司无线网络居然断掉了,郁闷.....   先来张效果图吧,这是仿CF界面做的一个Demo,因为个人没有美工能力,所以这个透明PNG图片处理的十分粗糙,导致窗体看起来有锯齿.     有了上一章做理论铺垫,这一章就直接上代码吧: /* * To change this template, choose Tools | Templa...

yshjava 289

Java -Swing-学习笔记

Java -Swing-学习笔记 文章目录Java -Swing-学习笔记1. 基本组件2. 特殊容器2.1 JSplitPane2.2 JTabbedPane2.3 JLayeredPane、JDesktopPane、JInternalFrame3.拖放功能4.Java7新增的Swing功能4.1 用JLayer装饰组件4.2 透明、不规则形状窗口5.用JProgressBar、P...

xhh22900的博客 511

JDK 6 u10 中 Swing最新特性:增加透明窗体及不规则窗体功能

<br />支持透明和不规则窗口已经成为 AWT 和 Swing 团队长久以来梦寐以求的功能。尽管本机应用程序在主要操作系统上使用这项功能已经为时已久,但在核心 Java 中还不能使用它。即将发布的 “Consumer JRE”正在进行修改,也就是对 Java SE 6 进行重大更新。Java SE 6 将为创建不规则、全透明和每个像素透明的顶级窗口提供 API。<br /><br />历史<br />本机应用程序的开发人员通常在开发 UI 应用程序中享受了更高级的灵活性。但是为此而付出的代价是将应用程序限

hsdjhj的专栏 681
上一篇: Java安全结构 沙盒模型
下一篇: 企业服务总线解决方案剖析,第 1 部分: 企业服务总线的基本概念
dongtg
博客等级 码龄19年 16粉丝 16原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值