本帖最後由 tonyh 於 2016-8-8 11:00 編輯
在視窗程式設計中,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
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.ImageIcon;
- import javax.swing.JLayeredPane;
- public class Ch110{
-
- private JFrame fm;
- private JLayeredPane layers;
- private JLabel lb1,lb2,lb3,lb4,lb5,lb6;
-
- Ch110()
- {
- lb1=new JLabel(new ImageIcon(Ch110.class.getResource("pic/baby.png")));
- lb1.setBounds(355, 220, 101, 141);
- lb2=new JLabel(new ImageIcon(Ch110.class.getResource("pic/clock.png")));
- lb2.setBounds(420, 15, 106, 106);
- lb3=new JLabel(new ImageIcon(Ch110.class.getResource("pic/girl.png")));
- lb3.setBounds(-5, 125, 199, 335);
- lb4=new JLabel(new ImageIcon(Ch110.class.getResource("pic/room.jpg")));
- lb4.setBounds(0, 0, 576, 407);
- lb5=new JLabel(new ImageIcon(Ch110.class.getResource("pic/sofa.png")));
- lb5.setBounds(150, 238, 410, 193);
- lb6=new JLabel(new ImageIcon(Ch110.class.getResource("pic/window.jpg")));
- lb6.setBounds(30, 20, 317, 210);
-
- layers=new JLayeredPane();
- layers.setBounds(0, 0, 576, 407);
- layers.add(lb1, new Integer(5));
- layers.add(lb2, new Integer(3));
- layers.add(lb3, new Integer(6));
- layers.add(lb4, new Integer(1));
- layers.add(lb5, new Integer(4));
- layers.add(lb6, new Integer(2));
-
- fm=new JFrame("JLayerPane");
- fm.setBounds(100, 100, 580, 435);
- fm.setVisible(true);
- fm.setResizable(true);
- fm.setLayout(null);
- fm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fm.add(layers);
- }
- public static void main(String[] args) {
- new Ch110();
- }
- }
複製代碼 |