小编典典
根据要实现的目标,您可以采用多种可能的方法。
基本方法是简单地绘制图形和摆动Timer
这样您就可以简单地更新一个变量,该变量将作为绘制大小的基础,例如…
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DrawerPaneTest {
public static void main(String[] args) {
new DrawerPaneTest();
}
public DrawerPaneTest() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new DrawerPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DrawerPane extends JPanel {
private boolean drawIn = false;
private Timer timer;
private int drawWidth = 0;
private int drawDelta = 4;
public DrawerPane() {
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
timer.stop();
drawIn = !drawIn;
drawDelta = drawIn ? 4 : -4;
timer.start();
}
});
timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
drawWidth += drawDelta;
if (drawWidth >= getWidth() / 2) {
drawWidth = getWidth() / 2;
timer.stop();
} else if (drawWidth < 0) {
drawWidth = 0;
timer.stop();
}
repaint();
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.drawRect(0, 0, drawWidth, getHeight());
g2d.dispose();
}
}
}
这真的很基础,并且没有考虑到概念变慢/变慢等问题。对于这些,您最好看一下专用的动画框架,例如
您可能使用哪种取决于您要实现的目标,我个人喜欢Timing
Framework,主要是因为它给了我很大的自由度,例如Trident之类的东西(主要是)旨在提供更改属性的能力。一个对象,例如大小或位置。尽管时序框架可以做到这一点,但要达到这一点还需要做更多的工作。
我没有使用Universal Tween引擎,但是看到了一些非常不错的示例,例如Sliding-
Layout,它实际上可以满足您的需求…
2020-11-30