2017-05-09 49 views
-1

下面是代碼,當圖像放到背景上時,無論我添加什麼代碼來移動它,它都會停留在左側牆上。我試過setLocation和setBounds。我想要做的就是將圖像移動到左下方,但不完全放在框架的牆上。如何移動卡住且不會移動的JLabel?

JFrame window = new JFrame(); 
window.setSize(800,480); 
window.setTitle("Battle"); 
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
window.setLayout(new BorderLayout()); 
JLabel background = new JLabel(); 
ImageIcon icon = new ImageIcon("background2.png");  
background.setIcon(icon); 
background.setLayout(new BorderLayout()); 
window.setContentPane(background); 
JLabel p1 = new JLabel(); 
p1 = a.getImage(); 
background.add(p1); 
p1.setLocation(500,500); 
p1.setVisible(true); 
window.setVisible(true); 
+0

BorderLayout這是做它的工作。您對setLocation的調用沒有任何意義,因爲BorderLayout像任何佈局管理器一樣,決定放置子組件的位置。您可能需要學習如何使用[GridBagLayout](http://docs.oracle.com/javase/8/docs/api/java/awt/GridBagLayout.html),但首先,您需要了解[如何LayoutManagers通常工作](https://docs.oracle.com/javase/tutorial/uiswing/layout/)。 – VGR

回答

3
window.setLayout(new BorderLayout()); 
... 
window.setContentPane(background); 

第一條語句,因爲第二條語句替換框架的內容窗格中,佈局管理器將是任何佈局管理器,你的「背景」部分設置沒有做任何事情。

所有我想要做的是圖像移動到左下角,

那麼你的佈局管理器設置爲BorderLayout的,所以你需要採取的BorderLayout的優勢。有關工作示例,請參閱How to Use BorderLayout的Swing教程中的部分。

所以,你需要做的第一件事就是指定適當的約束,以在底部顯示的組件:

//background.add(p1); // defaults to BorderLayout.CENTER if no constraint is specified 
background.add(p1, BorderLayout.PAGE_END); 

測試此,圖像會在底部,但它仍然是居中。

所以,現在你需要設置標籤的屬性告訴標籤來繪圖左對齊:

label.setHorizontalAlignment(JLabel.LEFT); 

沒有完全框架

如果你的牆壁上圖像周圍需要額外的空間,那麼你可以添加一個Border到標籤。使用上面的鏈接閱讀How to Use Borders上的教程部分。您可以使用EmptyBorder來提供額外的空間。要做到這一點

1

的一種方法是增加額外的「左面板」的容器,所以我們可以在左邊的位置您的標籤和底部

public static void main(String[] args) { 
    JFrame window = new JFrame(); 
    window.setSize(800, 480); 
    window.setTitle("Battle"); 
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    JLabel background = new JLabel(); 
    background.setBackground(Color.gray); 
    background.setLayout(new BorderLayout()); 
    background.setOpaque(true); 
    window.setContentPane(background); 

    JPanel leftPanel = new JPanel(); 
    leftPanel.setLayout(new BorderLayout()); 
    background.add(leftPanel, BorderLayout.WEST); // stick our left side bard to the left side of frame 

    JLabel p1 = new JLabel(); 
    p1.setText("Im here"); 
    p1.setLocation(500, 500); 
    p1.setVisible(true); 
    p1.setBackground(Color.black); 
    p1.setOpaque(true); 
    leftPanel.add(p1, BorderLayout.SOUTH); // add our label to the bottom 
    window.setVisible(true); 
} 

結果: enter image description here