一、具体需求:我们需要JLabel在一个背景上移动
二、解决办法:将JLabel和背景层分层放置,更具体的解释在代码中给出了
三、具体代码:
public class Practice extends JFrame {
private static final long serialVersionUID = 1L;
JLabel jLabel = new JLabel("A String Or A Picture");
private JLayeredPane layeredPane = this.getLayeredPane();
private BackgroundPanel backgroundPanel = new BackgroundPanel();
public Practice() {
setSize(400,400);
//将背景层放到layer层的底层
layeredPane.add(backgroundPanel,JLayeredPane.DEFAULT_LAYER);
//将Jlabel放到layer层的高层
layeredPane.add(jLabel,JLayeredPane.MODAL_LAYER);
this.setLayout(null);//如果不设置这个,jLabel无法设置位置
//设置jLabel的位置
jLabel.setBounds(10, 200, 150, 20);
setVisible(true);
}
public void jLabelForward(int x) {
jLabel.setBounds(jLabel.getBounds().x + x, 200, 150, 20);
}
class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 1L;
public BackgroundPanel() {
setSize(400,400);
}
/**
* 使用Graphics画图,然后作为背景,你可以自定义背景,不画图也可以
*/
public void paintComponent(java.awt.Graphics g) {
g.drawLine(200, 10, 200, 300);
}
}
public static void main(String[] args) throws InterruptedException {
Practice practice = new Practice();
//每秒移动一次,移动四次
for(int i = 0;i<4;i++) {
Thread.sleep(1000);
practice.jLabelForward(50);
}
}
}
四、拓展
1、JFrame的视图层的顺序如下图所示
2、为什么我要写这一片博客?
因为试了在很多博客看的参考方法,在不涉及线程的时候工作正常,一旦涉及线程,就会出现很奇怪的错误,如下图所示