在視窗程式設計中,JFrame、JPanel、JLayeredPane都是所謂的容器。當視窗裡的元件需依照指定的順序前後交疊,我們可利用 JLayeredPane 容器來指定圖層的順序,透過該類別下的 add(Component comp, Object constraints) 方法,先將元件加入 JLayeredPane 容器,再加入 JFrame 容器。
在本單元練習中,視窗中有六個元件:房間、沙發、窗戶、掛鐘、嬰兒、小丸子。試將這六個元件放入 JLayeredPane 容器並指定圖層 1 到 6,使其可前後交疊,如範例輸出畫面。
各元件的設定如下:
JFrame:100, 100, 580, 435
JLayeredPane:0, 0, 576, 407
房間:0, 0, 576, 407
沙發:150, 238, 410, 193
窗戶:30, 20, 317, 210
掛鐘:420, 15, 106, 106
嬰兒:355, 220, 101, 141
小丸子:-5, 125, 199, 335
素材: pic.zip
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JLayeredPane;
- import javax.swing.ImageIcon;
- public class Ch105 {
- private JFrame fm;
- private JLayeredPane lp;
- private JLabel lb_baby,lb_clock,lb_girl,lb_room,lb_sofa,lb_window;
-
- Ch105()
- {
- lb_baby=new JLabel(new ImageIcon(Ch105.class.getResource("pic/baby.png")));
- lb_clock=new JLabel(new ImageIcon(Ch105.class.getResource("pic/clock.png")));
- lb_girl=new JLabel(new ImageIcon(Ch105.class.getResource("pic/girl.png")));
- lb_room=new JLabel(new ImageIcon(Ch105.class.getResource("pic/room.jpg")));
- lb_sofa=new JLabel(new ImageIcon(Ch105.class.getResource("pic/sofa.png")));
- lb_window=new JLabel(new ImageIcon(Ch105.class.getResource("pic/window.jpg")));
- lb_baby.setBounds(355, 220, 101, 141);
- lb_clock.setBounds(420, 15, 106, 106);
- lb_girl.setBounds(-5, 125, 199, 335);
- lb_room.setBounds(0, 0, 576, 407);
- lb_sofa.setBounds(150, 238, 410, 193);
- lb_window.setBounds(30, 20, 317, 210);
-
- lp=new JLayeredPane();
- lp.setBounds(0, 0, 576, 407);
- lp.add(lb_room, new Integer(1));
- lp.add(lb_sofa, new Integer(2));
- lp.add(lb_window, new Integer(3));
- lp.add(lb_clock, new Integer(4));
- lp.add(lb_baby, new Integer(5));
- lp.add(lb_girl, new Integer(6));
-
- fm=new JFrame("JLayeredPane 練習");
- fm.setBounds(100, 100, 580, 435);
- fm.setVisible(true);
- fm.setResizable(false);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.add(lp);
- }
- public static void main(String[] args) {
- new Ch105();
- }
- }
複製代碼 |