在Mac OS X中,当在不同的选项卡之间切换时(例如系统偏好设置窗口),一些窗口会使用逐渐动画(增大/缩小)来改变其大小。
如何在JFrame(Java)中实现这种效果,而不会出现视觉闪烁或性能下降,是最好的方法。
谢谢。
谢谢。
缩小一点
new Thread(new Runnable()
{
public void run()
{
Dimension dim = jframe.getSize();
while (dim.getHeight() >= someheightintegeryouwanttoshrintto)
{
try
{
jframe.setSize((int)(dim.getWidth()), (int)(dim.getHeight()-1));
Thread.sleep(1);
}
catch(InterruptedException ex)
{
}
dim = jframe.getSize();
}
}
}).start();
成长一点
new Thread(new Runnable()
{
public void run()
{
Dimension dim = jframe.getSize();
while (dim.getHeight() <= sometheightyouwanttoincreaseto)
{
try
{
jframe.setSize((int)(dim.getWidth()), (int)(dim.getHeight()+1));
Thread.sleep(1);
}
catch(InterruptedException ex)
{
}
dim = jframe.getSize();
}
}
}).start();
我使用单个JFrame,在替换JPanels后调整其大小。这会产生Mac OS X风格的动画效果(可能需要在LauncherTask类中进行一些参数更改,以使其更完美地进行动画)
我将这行代码放在主JFrame类即Launcher.java中。Configuration类扩展了JPanel类,我使用this.setPreferredSize()来设置它的大小(这将在LauncherTask类中用于相应地调整大小)
(new Thread(new Configuration(this))).start();
这是一个用于调整JPanel大小的类文件
package com.imoz;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
public class LauncherTask extends SwingWorker<Void, Void> {
float x,y,dx,dy,pixel;
private JFrame parent;
private Dimension target;
public LauncherTask(JFrame parent, Dimension target) {
this.parent = parent;
this.target = target;
}
@Override
protected Void doInBackground() throws Exception {
dx = (float) Math.abs(parent.getWidth() - target.getWidth());
dy = (float) Math.abs(parent.getHeight() - target.getHeight());
if( dx >= dy )
pixel=dx;
else
pixel=dy;
pixel /= 7.5;
dx=dx/pixel;
dy=dy/pixel;
x=parent.getWidth();
y=parent.getHeight();
boolean dxGrow = true, dyGrow = true;
if(parent.getWidth() < target.getWidth())
dxGrow = false;
if(parent.getHeight() < target.getHeight())
dyGrow = false;
float i = 1f;
while(i <= pixel)
{
if(dxGrow)
x -= dx;
else
x += dx;
if(dyGrow)
y -= dy;
else
y += dy;
parent.setSize((int)x, (int)y);
parent.setLocationRelativeTo(null);
parent.invalidate();
i+=1;
}
parent.setSize((int)target.getWidth(), (int)target.getHeight());
parent.setLocationRelativeTo(null);
return null;
}
}