本文使用SwingX與TimingFramework展示了如何實現淡入淡出效果,程序簡潔 實用,希望對大家能有所助益。
在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 }