flywithmoon
发贴: 44
积分: 0
|
于 2004-08-24 22:40
以下代码无法实现面板背景颜色的不间断随机变化,请教高手如何修改: import java.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; class test extends JFrame implements Runnable { test(){ Thread t=new Thread(this); this.getContentPane().add(new myp()); t.start(); } public static void main(String args []){ test f=new test(); f.setSize(300,300); f.show(); } public void run() { while(true) { try{ Thread.sleep(1500);repaint(); System.out.print("hhh"); }catch(Exception e){e.printStackTrace();} } } } class myp extends JPanel implements ActionListener { JButton jb1,jb2,jb3,jb4; myp() { setLayout(new GridLayout(2,2)); JPanel p1=new JPanel(); p1.setBackground(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); add(p1);jb1=new JButton("1"); p1.add(jb1); JPanel p2=new JPanel(); p2.setBackground(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); add(p2);jb2=new JButton("2"); p2.add(jb2); JPanel p3=new JPanel(); p3.setBackground(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); add(p3);jb3=new JButton("3"); p3.add(jb3); JPanel p4=new JPanel(); p4.setBackground(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); add(p4);jb4=new JButton("4"); p4.add(jb4); jb1.addActionListener(this); jb2.addActionListener(this); jb3.addActionListener(this); jb4.addActionListener(this);repaint(); }
public void actionPerformed(ActionEvent e) { Graphics g=getGraphics(); if(e.getActionCommand().equals("1")) { g.setColor(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); g.fillRect(50,50,60,80);} if(e.getActionCommand().equals("2")) { g.setColor(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); g.fillArc(190,50,100,100,30,120); } if(e.getActionCommand().equals("3")) { g.setColor(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); g.fillOval(50,180,50,50); } if(e.getActionCommand().equals("4")) { g.setColor(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255))); g.drawString("Hello",200,200); } } }
|