利用SwingX与TimingFramework实现淡入淡出
本文使用SwingX与TimingFramework展示了如何实现淡入淡出效果,程序简洁实用,希望对大家能有所助益。(2009.09.28最后更新)
在Swing中使用AlphaComposite设置界面的半透明度,再配合javax.swing.Timer可以比较容易地实现淡入淡出效果。但需要我们继承具体的UI组件,并重写它的paintComponent方法,同时还要为Timer提供一个ActionListener的实现。这些对于程序员来说,显得有些乏味。
幸运地是,SwingX中的JXPanel(JPanel的子类)通过setAlpha方法来设置半透明度,JXPanel中的所有UI组件都可随之半透明化。TimingFramework提供的Animator可以帮助我们非线性地设置JXPanel中的alpha值。故,我们在实现淡入淡出时,可以使用JXPanel来替代JPanel,用Animator来替代Timer。
下面是一个非常简单的示例,该示例在一个使用CardLayout的JPanel--cardPanel,中另包含了两个JXPanel--panelA和panelB,这两个子容器中又分别有一个JButton--buttonA和buttonB。当点击buttonA时,将淡入显示panelB;当点击buttonB时,将淡入显示panelA。
1 public class FadingCardDemo extends JFrame {
2
3 private static final long serialVersionUID = 8005909309849021746L;
4
5 private String CARD_A = "CARD_A";
6 private String CARD_B = "CARD_B";
7
8 private JPanel cardPanel = null;
9 private JXPanel panelA = null;
10 private JXPanel panelB = null;
11 private JButton buttonA = null;
12 private JButton buttonB = null;
13
14 public FadingCardDemo() {
15 super("FadingButton Demo");
16 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17 initUI();
18 }
19
20 private void initUI() {
21 cardPanel = new JPanel(new CardLayout());
22
23 buttonA = new JButton("Button A");
24 buttonA.addActionListener(actionHandler);
25 panelA = new JXPanel(new BorderLayout());
26 panelA.add(buttonA, BorderLayout.CENTER);
27 cardPanel.add(panelA, CARD_A);
28
29 buttonB = new JButton("Button B");
30 buttonB.addActionListener(actionHandler);
31 panelB = new JXPanel(new BorderLayout());
32 panelB.add(buttonB, BorderLayout.CENTER);
33 cardPanel.add(panelB, CARD_B);
34
35 Container container = getContentPane();
36 container.setLayout(new BorderLayout());
37 container.add(cardPanel, BorderLayout.CENTER);
38 }
39
40 private ActionListener actionHandler = new ActionListener() {
41
42 private Animator animator = null;
43
44 public void actionPerformed(ActionEvent e) {
45 if (animator == null) {
46 animator = new Animator(2000);
47 animator.setDeceleration(0.2F);
48 animator.setAcceleration(0.4F);
49 } else if (animator.isRunning()) {
50 animator.stop();
51 }
52
53 JButton button = (JButton) e.getSource();
54 if (button == buttonA) {
55 animator.addTarget(new PropertySetter(panelB, "alpha", 1.0F));
56 panelB.setAlpha(0.1F);
57 ((CardLayout) cardPanel.getLayout()).show(cardPanel, CARD_B);
58 } else if (button == buttonB) {
59 animator.addTarget(new PropertySetter(panelA, "alpha", 1.0F));
60 panelA.setAlpha(0.1F);
61 ((CardLayout) cardPanel.getLayout()).show(cardPanel, CARD_A);
62 }
63 animator.start();
64 }
65 };
66
67 public static void main(String[] args) {
68 SwingUtilities.invokeLater(new Runnable() {
69 public void run() {
70 FadingCardDemo demo = new FadingCardDemo();
71 demo.setSize(new Dimension(400, 300));
72 demo.setVisible(true);
73 }
74 });
75 }
76 }