我正在尝试在我的 Swing 应用程序中开发类似 Toast (Android) 的功能。作为一个独立的,它完美地工作。但是当集成到应用程序中时,它会带来问题。
类文件是:
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.geom.RoundRectangle2D;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JLabel;
import net.mindcrew.utils.LayoutHelper.Packer;
public class Toast extends JDialog {
String text;
public Toast(String text) {
this.text = text;
initComponents();
}
private void initComponents(){
setLayout(new GridBagLayout());
addComponentListener(new ComponentAdapter() {
// Give the window an rounded rect shape. LOOKS GOOD
// If the window is resized, the shape is recalculated here.
@Override
public void componentResized(ComponentEvent e) {
setShape(new RoundRectangle2D.Double(0,0,getWidth(),getHeight(),50,50));
}
});
setUndecorated(true);
setSize(300,100);
setLocationRelativeTo(null);
getContentPane().setBackground(Color.BLACK);
// Determine what the GraphicsDevice can support.
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
final boolean isTranslucencySupported =
gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.TRANSLUCENT);
//If shaped windows aren't supported, exit.
if (!gd.isWindowTranslucencySupported(GraphicsDevice.WindowTranslucency.PERPIXEL_TRANSPARENT)) {
System.err.println("Shaped windows are not supported");
}
//If translucent windows aren't supported,
//create an opaque window.
if (!isTranslucencySupported) {
System.out.println(
"Translucency is not supported, creating an opaque window");
}
// Set the window to 70% translucency, if supported.
if (isTranslucencySupported) {
setOpacity(0.9f);
}
ImageIcon loading = new ImageIcon(Toast.class.getResource("/net/mindcrew/utils/userinterface/resources/loading-photo.gif"));
JLabel label = new JLabel(text);
label.setForeground(Color.WHITE);
label.setIcon(loading);
Packer packer = new Packer(this);
packer.pack(label).fillboth().west().inset(0, 50, 0, 20);
}
public static Toast showDailog(String textToDisplay){
final Toast toast = new Toast(textToDisplay);
// Display the window.
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
toast.setVisible(true);
}
});
thread.start();
return toast;
}
@Override
public void hide(){
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
setVisible(false);
dispose();
}
});
}
public static void main(String... args){
Toast toast = Toast.showDailog("Display");
try{
Thread.sleep(5000);
}
catch (Exception e){}
toast.hide();
}
}
可能存在一些实现错误,但这是基本的事情。
这很好用。但是,当我试图以资源密集型操作的方式进行操作时,它会跳闸。由于 GIF 动画没有出现,我认为这意味着它有点停滞不前。
用途是:
Toast toast = Toast.showDailog("Generating PDF");
//resource intensive operation. Takes about 3-5seconds to execute
toast.hide();
更让我痛苦的是,即使在“Toast”被处理之后,应用程序也变得非常缓慢。我很确定减速不是因为有问题的操作,因为如果我取消“吐司”,它可以完美地工作。
有人可以指出这里有什么问题吗???
我经历了这个问题。但是那里的事情比我要找的要复杂得多。我正在寻找的是一个简单的对话框。不是需要容纳多个组件的完整框架。