第一步:先构建窗体
第二部:new几个按钮
第三部 :通过按钮实现监听
第四部:使用线程达到动态效果。
代码如下:
public class TanMu extends JFrame {
public TanMu() {
this.setBounds(50, 50, 600, 400);
this.setTitle("movie");
JMenuBar bar = new JMenuBar();
JButton b1 = new JButton("花美男");
JButton b2 = new JButton("绿茶婊");
JButton b3 = new JButton("帅哥");
JButton b4 = new JButton("美女");
b1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
b1.setBounds(100, 30, 100, 20);
}
});
new Thread(new Runnable() {
@Override
public void run() {
int x = 100;
while (true) {
x += 5;
if (x > 600) {
x = -100;
}
try {
Thread.sleep(80);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// b1.setBounds(100, 30, 100, 20);
b1.setBounds(x, 30, 100, 20);
}
}
}).start();
b2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
b2.setBounds(200, 130, 100, 20);
}
});
new Thread(new Runnable() {
@Override
public void run() {
int x = 200;
while (true) {
x += 8;
if (x > 600) {
x = -100;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b2.setBounds(x, 130, 100, 20);
}
}
}).start();
b3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
b3.setBounds(300, 230, 100, 20);
}
});
new Thread(new Runnable() {
@Override
public void run() {
int x = 300;
while (true) {
x += 10;
if (x > 600) {
x = -100;
}
try {
Thread.sleep(60);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b3.setBounds( x, 230, 100, 20);
}
}
}).start();
b4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
b4.setBounds(400, 330, 100, 20);
}
});
new Thread(new Runnable() {
@Override
public void run() {
int x = 400;
while (true) {
x += 6;
if (x > 600) {
x = -100;
}
try {
Thread.sleep(70);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
b4.setBounds( x, 330, 100, 20);
}
}
}).start();
Container c = this.getContentPane();
c.add(b1);
c.add(b2);
c.add(b3);
c.add(b4);
c.setLayout(null);// 返璞归真
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new TanMu();
}
}