1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| package 线程; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Timer; import java.util.TimerTask;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel;
import javax.swing.JPanel;
public class MutilThreadDemo extends JFrame{ JPanel jPanel=null; JLabel jLabel=null; JButton jButton=null; String word[]= {"桐乃","小埋","宫子","日向"}; int index=0; int movex=5; public MutilThreadDemo() { jPanel=new JPanel(); jLabel=new JLabel(word[0]); jButton=new JButton("左右横移"); jLabel.setFont(new Font("黑体",Font.BOLD,28)); jLabel.setBounds(80,50,250,50); jButton.setBounds(0,150,120,25); jPanel.add(jLabel); jPanel.add(jButton); this.add(jPanel); this.setSize(500,300); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); new ChangeColor().start(); new Timer().schedule(new ChangeWord(), 0,1000); new javax.swing.Timer(100, new ChangePos()).start(); } class ChangeColor extends Thread{ @Override public void run() { while (this.isAlive()) { int r=(int)(Math.random()*256); int g=(int)(Math.random()*256); int b=(int)(Math.random()*256); jPanel.setBackground(new Color(r,g,b)); try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } } } class ChangeWord extends TimerTask{ @Override public void run() { jLabel.setText(word[index++]); if(index==word.length) index=0; } } class ChangePos implements ActionListener{ @Override public void actionPerformed(ActionEvent arg0) { int x=jButton.getX()+movex; if(x<=0) { x=0; movex=-movex; }else if(x>=getWidth()-jButton.getWidth()) { x=getWidth()-jButton.getWidth(); movex=-movex; } jButton.setLocation(x,jButton.getY()); } } public static void main(String[] args) { MutilThreadDemo mutilThreadDemo=new MutilThreadDemo(); mutilThreadDemo.setVisible(true); } }
|