我编写了一个Swing登录框,有设置背景,但是外层的jpanel会把背景覆盖掉,感觉很丑,要怎么设置透明,各位大神帮帮忙!
代码如下:
public class UserLogin extends JFrame{
private Graphics g;
//构造函数
public UserLogin(){
//加载背景图片
final ImageIcon icon = new ImageIcon(“D:\workspace\images\bg_login.jpg”);
JPanel container = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(icon != null){
g2d.drawImage(icon.getImage(), 0, 0, getWidth(), this.getHeight(), this);
}
}
};
//logo图片
JLabel lblIamge = new JLabel();
ImageIcon admin_p = new ImageIcon(“D:\workspace\images\admin_p.gif”);
lblIamge.setIcon(admin_p);
//用户名、密码、登录
JTextField tfUserName = new JTextField(15);
JPasswordField pfPassword = new JPasswordField(15);
JButton bntLogin = new JButton(“登录”);
tfUserName.setBackground(null);
tfUserName.setOpaque(false);
pfPassword.setOpaque(false);
JPanel center_right = new JPanel();
center_right.setLayout(new GridLayout(3,1,10,10));
center_right.setBackground(null);
center_right.setOpaque(false);
center_right.add(tfUserName);
center_right.add(pfPassword);
center_right.add(bntLogin);
JPanel center = new JPanel();
center.add(lblIamge);
center.add(center_right);
container.add(center);
//this.setBounds(0,0,400,300);
this.setSize(400,300); //设置窗口大小
this.setLocationRelativeTo(null); //设置窗口居中
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(container);
this.setVisible(true);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new UserLogin();
}
});
}
运行后的效果: