簡體   English   中英

如何移動卡住且不會移動的JLabel?

[英]How do I move a JLabel that is stuck and won't move?

這是代碼,當圖像放置到背景上時,無論我添加什么代碼來移動它,它都只會停留在左牆上。 我嘗試過setLocation和setBounds。 我要做的就是將圖像移到左下角,但不完全移到框架的牆上。

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);
window.setLayout(new BorderLayout());
...
window.setContentPane(background);

第一條語句不執行任何操作,因為第二條語句替換了框架的內容窗格,而布局管理器將是您為“背景”組件設置的任何布局管理器。

我要做的就是將圖像移到左下角,

好了,您將布局管理器設置為BorderLayout,因此您需要利用BorderLayout的優勢。 閱讀Swing教程中有關如何使用BorderLayout的部分, 獲取工作示例。

因此,您需要做的第一件事是指定適當的約束以使組件顯示在底部:

//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來提供額外的空間。

一種方法是添加額外的“左側面板”容器,以便我們可以將標簽放置在左側和底部

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);
}

結果: 在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM