2009-11-19 127 views
11

我想添加一個JLayeredPane到JPanel,然後添加一個圖像(JLabel圖標)和一個按鈕到JLayeredPane,但都沒有出現。我已經測試了沒有按鈕和分層面板的圖像,所以我知道這很有用。這裏是我使用的一些代碼。有什麼我失蹤或做錯了嗎?將JLayeredPane添加到JPanel

 

public class MyClass extends JPanel 
{ 
    private JLayeredPane layeredPane; 
    private JLabel imageContainer = new JLabel(); 
    private JButton info = new JButton("i"); 

    MyClass(ImageIcon image) 
    { 
     super(); 

     this.imageContainer.setIcon(image); 

     this.layeredPane = new JLayeredPane(); 
     layeredPane.setPreferredSize(new Dimension(300, 300)); 
     layeredPane.add(imageContainer, new Integer(50)); 
     layeredPane.add(info, new Integer(100)); 

     this.add(layeredPane); 
    } 
}  
 
+1

沒有看到在哪裏以及如何將MyClass添加到某種框架中,因此沒有告訴您出錯的地方 – 2009-11-19 15:39:25

回答

15

tutorial

默認情況下,一個分層窗格沒有佈局管理器。這意味着您通常必須編寫定位和調整放置在分層窗格中的組件的代碼。

看到的變化對您的代碼:

import java.awt.*; 
import javax.swing.*; 
public class MyClass extends JPanel { 
    private JLayeredPane layeredPane; 
    private JLabel imageContainer = new JLabel(); 
    private JButton info = new JButton("i"); 

    MyClass(ImageIcon image) { 
     super(); 

     this.imageContainer.setIcon(image); 

     this.layeredPane = new JLayeredPane(); 
     layeredPane.setPreferredSize(new Dimension(300, 300)); 
     layeredPane.add(imageContainer, new Integer(50)); 
     layeredPane.add(info, new Integer(100)); 
     this.add(layeredPane); 
     // CHANGED CODE 
     // Manually set layout the components. 
     imageContainer.setBounds(0, 0, 
            image.getIconWidth(), 
            image.getIconHeight()); 
     info.setBounds(200, 00, 50, 40); 
    } 
    public static void main(String [] args) { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new MyClass(new ImageIcon("logo.png") )); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
}  

其他注意事項:

1)它是更好的(在我看來),以將左大括號在同一行。這就是大多數Java代碼的樣子。 2)避免從JPanel(或任何其他組件)繼承,如果你不真的創建子類。您可以直接使用它,而不必繼承(除非您確實創建了一個新組件)。

+2

謝謝你的回答!爲了迴應這個大括號的評論,我不這樣做的原因是由於空白的可讀性。我覺得這是一個視覺設計問題,因爲它沒有proformance影響。它幫助我和我知道它可以幫助那些不熟悉代碼的其他人(不是全部) – asawilliams 2009-11-19 17:21:11

+0

@asawilliams:確實它沒有其他影響,但代碼可讀性。如果你已經意識到這種風格,並且你有意避免它,我認爲它是可以的。無論如何,我會爲那些不知道它的人推薦這個建議,我發現來自其他編程語言的開發人員拒絕採用這種風格。在其他花括號編程語言之前?至於幫助,不用客氣;) – OscarRyz 2009-11-19 17:57:09

+0

是啊,C,C++,C#,Actionscript 3,php,...。這正是我被教導的方式。我可以理解一些程序員喜歡使用緊密代碼,但除了首選項之外,我沒有看到任何其他原因。 – asawilliams 2009-11-19 18:06:04

4

JLayeredPane的默認有一個空的佈局管理器,所以在你的榜樣,您需要設置子組件的位置和大小。您可以在JLayeredPane上設置佈局管理器,但這很可能會否定我想要的分層渲染,因爲您正在使用分層窗格。