Swing JPanel重绘 如何控制按钮位置

import java.awt.Graphics;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class LayerTest {

public static void main(String[]args){
    JFrame jf = new JFrame("JPANEL 分层");
    jf.setBounds(100, 100, 500, 280);


    JPanel jp = new JPanel(){
        @Override
        protected void paintComponent(Graphics g) {
            // TODO Auto-generated method stub
            super.paintComponent(g);
            URL imgURL = getClass().getResource("/images/login.jpg");
            ImageIcon icon=new ImageIcon(imgURL);
            g.drawImage(icon.getImage(),0,0,getSize().width,getSize().height,this);
        }
    };
    JButton btn = new JButton("Test");
    btn.setLocation(100, 180); [color=red]//按钮位置设置无效,显示在顶部居中[/color] 
         jp.setOpaque(true);
         jp.add(btn);
    jf.getContentPane().add(jp);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    jf.setVisible(true);
}

}

给你的JPanel加一个布局,如:jp.setLayout(new GridBagLayout());
然后你就可以按照你自己的布局去调整。