2016-09-13 23 views
0

我創造了這個代碼做問答&使用圖標作爲背景一件事:如何在Jlabel頂部使用Jtextfield?

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.*; 
import javax.swing.*; 
public class test 
{ 
    private JFrame frame; 
    private JLabel label; 
    private JLabel bg; 
    private Jbutton button1; 
    private ImageIcon icon; 
    private JTextField tf; 
    public test(){ 
     run(); 
    } 
    public void run(){ 
     frame = new JFrame("Test"); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(600, 400); 

     icon = new ImageIcon("My_Path"); 
     bg = new JLabel(icon); 
     bg.setLayout(new FlowLayout()); 

     frame.getContentPane().setLayout(new FlowLayout()); 
     tf = new JTextField("text field",100); 
     tf.setHorizontalAlignment(JTextField.CENTER); 
     frame.getContentPane().add(tf); 

     button1 = new JButton("Check!"); 
     button1.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent e){ 
       /*action*/ 
      } 
     }); 

     frame.add(bg); 

     label = new JLabel("text"); 
     bg.add(label); 
     bg.add(button1); 
    } 
    public void main(String[] args){ 
     new test(); 
    } 

,由於某種原因文本字段是「堵」的標籤,BG和讓它動。 我怎樣才能讓文本字段'超過'標籤bg中的圖標?

+0

您可能會在文本字段上設置文本字段的位置屬性,或者將其嵌套在標籤中 – mcraen

+0

「blocking」是什麼意思?如果你想在圖片頂部使用JTextField,請參閱http://stackoverflow.com/questions/8556626/how-do-i-put-jlabel-and-jtextfield-on-top-of-image – copeg

回答

0

你可以創建一個自定義的JPanel並覆蓋其的paintComponent方法,但它通常更容易,只需使用一個OverlayLayout

JComponent fields = new JPanel(new GridBagLayout()); 
fields.setOpaque(false); 

GridBagConstraints gbc = new GridBagConstraints(); 
gbc.gridwidth = GridBagConstraints.REMAINDER; 
gbc.anchor = GridBagConstraints.BASELINE_LEADING; 
fields.add(tf, gbc); 
gbc.insets.top = 6; 
fields.add(label, gbc); 
fields.add(button1, gbc); 

fields.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
fields.setAlignmentY(JComponent.CENTER_ALIGNMENT); 
bg.setAlignmentX(JComponent.CENTER_ALIGNMENT); 
bg.setAlignmentY(JComponent.CENTER_ALIGNMENT); 

JPanel overlay = new JPanel(); 
overlay.setLayout(new OverlayLayout(overlay)); 
overlay.add(fields); 
overlay.add(bg); 

frame.getContentPane().add(overlay); 

請注意,你應該叫frame.setVisible(true)添加組件到JFrame。