窗口颜色切换

来源:互联网 发布:什么云计算 编辑:程序博客网 时间:2024/06/05 22:36
/** * 编写一个线程改变窗体的颜色,详细要求如下: * 使用Runnable创建线程,该线程实现窗口的颜色在黑色和白色之间不断的切换。 * 使用内部类创建线程的方式,实现窗口的颜色在黑色和白色之间不断的切换。 * @param args */

知识点:

/** * JPanel  contentPane=new  JPanel();//把其它组件添加到Jpanel中;  * frame.setContentPane(contentPane);//把contentPane对象设置成为frame的内容面板 * @author Administrator * */

代码如下:

使用Runnable接口

public class Test extends JFrame implements Runnable{public void run(){JPanel panel = new JPanel();panel.setSize(300, 300);//设置画板尺寸//this代表独享t,谁调用run方法this指的就是谁this.setContentPane(panel); //将panel对象添加到JFrame中//设置背景变换int count =0;while(true){count = (count==0)? 1:0;//也可以利用求余数的方法switch(count){case 0:panel.setBackground(Color.BLACK);break;case 1:panel.setBackground(Color.WHITE);}try{Thread.sleep(100);//100毫秒切换一次}catch(InterruptedException e){e.printStackTrace();}}}public static void main(String[] args) {Test t = new Test();t.setSize(300, 300);//由于test继承了JFrame所以可以直接调用JFrame中的方法t.setAlwaysOnTop(true);//总在最上t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置默认关闭操作t.setLocationRelativeTo(null);//设置相对位置t.setVisible(true);//设置窗口可见Thread show = new Thread(t);show.start();}}
使用内部类

代码如下:

public class Test1 extends JFrame{public static void main(String[] args) {JFrame frame = new JFrame("测试窗口");frame.setSize(300, 300);frame.setAlwaysOnTop(true);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setLocationRelativeTo(null);JPanel panel = new JPanel();panel.setSize(300, 300);//frame.add(panel); 两句代码可以互换frame.setContentPane(panel);frame.setVisible(true);//窗口已经建立完成Thread t = new Thread(){public void run(){int count = 0;while(true){count = (count ==0)? 1:0;switch(count){case 0:panel.setBackground(Color.BLACK);break;case 1:panel.setBackground(Color.WHITE);}try {Thread.sleep(200);//200毫秒切换一次} catch (InterruptedException e) {e.printStackTrace();}}}};t.start();}}

还可以利用定时器来执行

代码如下:

//利用定时器设置窗口的切换public class Test10 extends JFrame{public static void main(String[] args) {JFrame frame = new JFrame("测试窗口");final JPanel panel = new JPanel();frame.add(panel);frame.setSize(300, 300);frame.setLocationRelativeTo(null);frame.setVisible(true);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setAlwaysOnTop(true);panel.setSize(300, 300);Timer timer = new Timer();timer.schedule(new TimerTask(){int count = 0;public void run(){count = (count == 0)? 1 : 0;switch(count){case 0:panel.setBackground(Color.BLACK);break;case 1:panel.setBackground(Color.BLUE);}}}, 4000, 1000);//经过4秒后run方法才开始执行,以后每隔1秒执行一次run方法}}



0 0
原创粉丝点击