import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class Applet extends JApplet{
private JTextField textField;
private JButton button;
private String str;
private Color color;
private JLabel label;
public void init() {
Container pane = getContentPane();
pane.setLayout(new BorderLayout());
textField = new JTextField();
button = new JButton();
label = new JLabel("请输入颜色:");
pane.add(label, BorderLayout.WEST);
pane.add(textField, BorderLayout.CENTER);
button.setText("确定");
pane.add(button, BorderLayout.EAST);
}
public void start(){
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
str = textField.getText(); // 获取textField的值
color = Color.decode(str); // 转换为颜色
textField.setText("pink");
getContentPane().setBackground(color);
}
});
}
}
------解决方案--------------------
color = Color.decode(str); //str的值是什么?str必须是8进制或16进制的数字字符串
textField.setText("pink"); //如果是这样的英文单词,是要抛出异常的
LZ自己查看javadoc就知道了
------解决方案--------------------
用反射吧
public void actionPerformed(ActionEvent e) {
try {
str = textField.getText(); // 获取textField的值
Field field = Color.class.getField(str.toUpperCase());
color = (Color)field.get(Color.class);
textField.setText(str);
getContentPane().setBackground(color);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}