|
欲实现Hello,Swing World !原先字体为绿色,点击按钮后,逐个变为红色,大家看看下面代码有什么问题,现在是点击按钮后,需要actionPerformed方法运行完后,变色后字体才有效,导致没达到效果,麻烦高手看下
java code
package com.test.oct27;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
*
*
*/
public class TAcionEvent extends JApplet {
/**
*
*/
private static final long serialVersionUID = 2169662119220746054L;
JLabel[] jls;
JButton jb;
String str;
int len;
JPanel jp;
Container container;
/**
* @throws HeadlessException
*/
public TAcionEvent() {
init();
addEvent();
}
public void init() {
jb = new JButton("start");
container = this.getContentPane();
str = "Hello,Swing World !";
len = str.length();
jls = new JLabel[len];
jp = new JPanel();
jp.setLayout(new GridLayout(1, len));
for (int i = 0; i < len; i++) {
jls = new JLabel(str.substring(i, i + 1));
jls.setForeground(Color.green);
jp.add(jls);
}
container.add(jp);
container.add(jb, BorderLayout.SOUTH);
}
public void addEvent() {
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (cmd.equals("start")) {
jb.setText("stop");
for (int i = 0; i < len; i++) {
jls.setForeground(Color.red);
delay();
}
} else {
jb.setText("start");
for (int i = 0; i < len; i++) {
jls.setText(str.substring(i, i + 1));
jls.setForeground(Color.green);
}
}
}
});
}
public void delay() {
for (int i = 0; i < 100000; i++) {
for (int j = 0; j < 10000; j++) {
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
JFrame jf = new JFrame("TAcionEvent");
TAcionEvent te = new TAcionEvent();
jf.getContentPane().add(te);
jf.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jf.setSize(300, 300);
jf.setVisible(true);
}
} |
|