日期:2014-05-20  浏览次数:20638 次

新手求教SWING 画界面问题
首先贴上我的程序,高手请勿笑,刚学几天而已

package demo.swing;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

public class LoginDemo
{

private static final String backgroundUrl="scroll.jpg";

private int width=100;

private int height=100;
/**
* @param args
*/
public static void main(String[] args)
{
new LoginDemo();
}

public LoginDemo()
{
JFrame jf=new JFrame("登陆页面");

jf.addWindowListener(new WindowAdapter()
{

@Override
public void windowClosing(WindowEvent arg0)
{
System.exit(0);
}
});


JPanel bg=getBackGroud();
bg.setBounds(0, 0, width, height);

JPanel login=getLoginWindow();
login.setBounds(0, 0, width, height);

jf.getLayeredPane().setLayout(null);

jf.getLayeredPane().add(bg,-1);
jf.setContentPane(login);

login.setOpaque(true);

jf.setSize(width, height);

jf.setVisible(true);

}

/**
* 获得背景
* @return
*/
private JPanel getBackGroud()
{
JPanel bg=new JPanel();
ImageIcon ii=new ImageIcon(this.getClass().getResource(backgroundUrl));
JLabel jl=new JLabel(ii);
this.width=ii.getIconWidth();
this.height=ii.getIconHeight();
bg.add(jl);
return bg;
}

/**
* 获得登陆界面
* @return
*/
private JPanel getLoginWindow()
{
JPanel win=new JPanel();
// win.setBounds(0, 0, width, height);

JLabel username=new JLabel("用户名");
username.setBounds(10, 10, 60, 20);
JTextField username_input=new JTextField(10);
username_input.setBounds(80, 10, 60, 20);

JLabel password=new JLabel("密码");
password.setBounds(10, 40, 60, 20);
JPasswordField password_input=new JPasswordField(10);
password_input.setBounds(80, 60, 60, 20);

win.add(username);
win.add(username_input);
win.add(password);
win.add(password_input);

return win;
}

}

发现几个问题

1 如果加入背景,则文字(用户名 密码)不显示出来

2 无法对其进行位置的调配,我想的是分为2行显示



还请高手 解答

------解决方案--------------------
用两个面板
------解决方案--------------------
jf.getLayeredPane().add(bg,-1); 改成jf.getLayeredPane().add(bg, new Integer(Integer.MIN_VALUE));
然后login.setOpaque(true); 改成login.setOpaque(false);
试试看
------解决方案--------------------
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

public class LoginDemo {

private static final String backgroundUrl = "scroll.jpg";

private int width = 300;

private int height = 200;

/**
* @param args
*/
public static void main(String[] args) {
new LoginDemo();
}

public LoginDemo() {
JFrame jf = new JFrame("login");

jf.addWindowListener(new WindowAdapter() {

@Override