2013-06-05 53 views
0

我已經添加了一張我想用作背景圖片的圖片,並且希望將jLabels放在上面。所以我使用圖像圖標功能並顯示圖像,但是當我嘗試將jLabel放在圖像上時,它會移到一邊。我嘗試了幾個教程,它似乎在YouTube上工作,但是當我嘗試單獨做同樣的事情時,他們會移出位置。NetBeans GUI Builder圖片

field.setIcon(new javax.swing.ImageIcon(getClass().getResource("/wiffleball/resources/field2.png"))); // NOI18N 
+0

你能發表你正在使用的代碼嗎? – MadProgrammer

+0

好的,這是代碼 –

+0

按標籤,你的意思是文本('JLabel')? – MadProgrammer

回答

1

默認情況下,JLabel沒有佈局管理器。唱片公司也有默認的文本定位,這通常是左對齊,您需要更改所有這些默認值...

enter image description here

您可能需要使用其他不同的佈局管理器BorderLayout,但這只是一個例子...

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.EventQueue; 
import java.awt.Font; 
import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class SimpleLabel { 

    public static void main(String[] args) { 
     new SimpleLabel(); 
    } 

    public SimpleLabel() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JLabel label = new JLabel(new ImageIcon("C:\\hold\\thumbnails\\_cg_836___Tilting_Windmills___by_Serena_Clearwater.png")); 
       label.setHorizontalAlignment(JLabel.CENTER); 
       label.setVerticalAlignment(JLabel.CENTER); 

       label.setLayout(new BorderLayout()); 

       JLabel child = new JLabel("Can you see me?"); 
       child.setForeground(Color.WHITE); 
       child.setFont(label.getFont().deriveFont(Font.BOLD, 24f)); 
       child.setHorizontalAlignment(JLabel.CENTER); 
       child.setVerticalAlignment(JLabel.CENTER); 
       child.setHorizontalTextPosition(JLabel.CENTER); 
       child.setVerticalTextPosition(JLabel.CENTER); 
       label.add(child); 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(label); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 
} 
+0

JLabel有一個佈局管理器,:-) [JLabel沒有任何LayoutManager](http:// stackoverflow.com/questions/8575641/how-returns-xxxsize-from-jcomponents-added-to-the-jlabel),從此屬性返回null – mKorbel

+0

@mKorbel或類似的東西;) – MadProgrammer

0

我把所有東西放在jPanel上,似乎這樣做。它只是採取了一些修補。謝謝!

相關問題