Java 如何在使用无线程延迟时更改JButtons的背景色?
我需要以这样一种方式编写一个程序:每个按钮都会发光,然后依次变暗。我不能使用线程,因为它们会同时发光,计时器似乎也不工作 我的代码:Java 如何在使用无线程延迟时更改JButtons的背景色?,java,swing,button,timer,delay,Java,Swing,Button,Timer,Delay,我需要以这样一种方式编写一个程序:每个按钮都会发光,然后依次变暗。我不能使用线程,因为它们会同时发光,计时器似乎也不工作 我的代码: import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; public class test extends JApplet { JButton a,b,c; JButton board[]=new JButton[3]; Co
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class test extends JApplet
{
JButton a,b,c;
JButton board[]=new JButton[3];
Color color;
public void makeGUI()
{
setLayout(new GridLayout(2,3));
a=new JButton("a");
b=new JButton("b");
c=new JButton("c");
a.setBackground(Color.red);
b.setBackground(Color.blue);
c.setBackground(Color.green);
add(a);
add(b);
add(c);
board[0]=(JButton)a;
board[1]=(JButton)b;
board[2]=(JButton)c;
glowing();
}
public void glowing()
{
for(int i=0;i<3;i++)
{
glow(i);
long start = System.currentTimeMillis( );
while(System.currentTimeMillis( ) - start < 2000){}
dim(i);
}
}
public void init()
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
public void run()
{
makeGUI();
}
});
}
catch(Exception exc)
{
System.out.println("can't create because of :"+exc);
}
}
public void glow(int x)
{
color=board[x].getBackground();
board[x].setBackground(color.brighter());
}
public void dim(int x)
{
board[x].setBackground(color);
}
}
import java.awt.*;
导入java.awt.event.*;
导入javax.swing.*;
导入java.util.*;
公共类测试扩展了JApplet
{
按钮a、b、c;
JButton board[]=新JButton[3];
颜色;
public void makeGUI()
{
setLayout(新网格布局(2,3));
a=新的按钮(“a”);
b=新的按钮(“b”);
c=新的按钮(“c”);
a、 挫折地面(颜色:红色);
b、 挫折背景(颜色:蓝色);
c、 挫折背景(颜色:绿色);
添加(a);
添加(b);
添加(c);
板[0]=(JButton)a;
板[1]=(JButton)b;
板[2]=(JButton)c;
发光的();
}
公共空间发光()
{
对于(int i=0;i而不是使用long start=System.currentTimeMillis();而(System.currentTimeMillis()-start<2000){}
要在发光和变暗之间暂停,您可能需要使用Thread.sleep()-cpu强度要低得多您想交错调光和发光吗?一次应该只有一个发光吗?最紧迫的问题是:您锁定了AWTEventQueue,这意味着UI将被完全锁定,直到发光
-方法终止。将这部分代码重新定位到,以获得一个正常工作的UIT此插图使用Swing定时器进行速率
@k.krol.27是的!一次应该发光。而不是使用long start=System.currentTimeMillis();而使用(System.currentTimeMillis()-start<2000){}
在发光和变暗之间暂停,您可能需要使用Thread.sleep()-cpu强度要低得多您想交错调光和发光吗?一次应该只有一个发光吗?最紧迫的问题是:您锁定了AWTEventQueue,这意味着UI将被完全锁定,直到发光
-方法终止。将这部分代码重新定位到,以获得一个正常工作的UIT此插图使用Swing定时器的费率
@k.krol.27是的!一次应该会发光。