2016-12-29 102 views
0

我想創建一個如此圖像的登錄幀(Login Frame)。 我使用setBounds()方法通過使用setBound來設置這些組件我將setLayout()設置爲null。現在我想添加一個背景圖像到我的登錄框架,但因爲我用setLayout()爲空,所以我無法設置圖像。試圖將背景圖像設置爲我的登錄幀

`public LoginFrame() 
    { 

    JFrame frame=new JFrame("Login"); 

      frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); 


     frame.setLayout(null); 

      uid=new JLabel("Email Id"); 
    uid.setBounds(60,50,120,25); 
      frame.add(uid); 

      tid=new JTextField(20); 
     tid.setBounds(120, 50,150,24); 
      frame.add(tid); 

      upass=new JLabel("Password"); 
    upass.setBounds(53,80,120,25); 
      frame.add(upass); 

      tpass=new JPasswordField(20); 
      tpass.setBounds(120, 80,150,24); 
       frame.add(tpass); 

       Login=new JButton("Login"); 
       Login.setBounds(150,110,80,25); 
       frame.add(Login); 

        frame.setSize(370,216); 
      frame.setResizable(false); 
      frame.setVisible(true); 

    frame.setLocationRelativeTo(null); 
    JLabel background=new JLabel(new ImageIcon("C:\\Users\\Tousif\\Desktop\\Login.jpg")); 
    add(background); 
} 

public static void main(String []arg) 
{ 
    new LoginFrame(); 
} 

}`

回答

0

試試這個,你需要使用setContentPane添加背景圖片。你需要添加背景圖片第一,那麼你需要添加其他對象,如標籤,文本框等。

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPasswordField; 
import javax.swing.JTextField; 

public class LoginFrame{ 
    public LoginFrame() { 
     JLabel uid, upass; 
     JTextField tid; 
     JPasswordField tpass; 
     JButton Login; 

     JFrame frame = new JFrame("Login"); 

     frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE); 

     frame.setLayout(null); 
     JLabel background = new JLabel(new ImageIcon(
       "C:\\Users\\Tousif\\Desktop\\Login.jpg")); 
     frame.setContentPane(background); 

     uid = new JLabel("Email Id"); 
     uid.setBounds(60, 50, 120, 25); 
     frame.add(uid); 

     tid = new JTextField(20); 
     tid.setBounds(120, 50, 150, 24); 
     frame.add(tid); 

     upass = new JLabel("Password"); 
     upass.setBounds(53, 80, 120, 25); 
     frame.add(upass); 

     tpass = new JPasswordField(20); 
     tpass.setBounds(120, 80, 150, 24); 
     frame.add(tpass); 

     Login = new JButton("Login"); 
     Login.setBounds(150, 110, 80, 25); 
     frame.add(Login); 

     frame.setSize(370, 216); 
     frame.setResizable(false); 


     frame.setLocationRelativeTo(null); 

     frame.setVisible(true); 
    } 

    public static void main(String[] arg) { 
     new LoginFrame(); 
    } 
} 
0

,但爲我所用的setLayout的()爲空,所以我不能設置圖像。

沒錯。不要使用空佈局。 Swing旨在與佈局經理一起使用。

舉個簡單的例子,你可以這樣做:

JLabel background = new JLabel(...); 
background.setLayout(new GridLayout(0, 2)); 
background.add(label1); 
background.add(textField1); 
background.add(label2); 
background.add(textField2); 
frame.add(background); 

如果你不喜歡的佈局,那麼用戶不同的Layout Manager