本题的功能是用按钮来控制文字的颜色。窗口中有三个按钮:“Yellow”、“Blue”和“Red”,它们分别对应文字标签中文本的颜色为黄色、蓝色和红色,点击任意一个按钮,文字标签中的文本就变成按钮对应的颜色。 import java.awt.*; impor

admin2012-12-02  45

问题 本题的功能是用按钮来控制文字的颜色。窗口中有三个按钮:“Yellow”、“Blue”和“Red”,它们分别对应文字标签中文本的颜色为黄色、蓝色和红色,点击任意一个按钮,文字标签中的文本就变成按钮对应的颜色。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ButtonPanel extends JPanel implements ActionListener{
public ButtonPanel(){
yellowButton = new JButton("Yellow");
blueButton = new JButton("Blue");
redButton = new JButton("Red");  
jl = new JLabel("I am from China!");
add(yellowButton);
add(blueButton);
add(redButton);
add(jl);
yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt){
Object source = evt.getSource();
Color color = getForeground();
if (source == yellowButton) color = Color.yellow;
else if (source == blueButton) color = Color.blue;
else if (source == redButton) color = Color.red;
______;
______;
}
private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
private JLabel jl;
}
class ButtonFrame extends JFrame{
public ButtonFrame(){
setTitle("exam_16");
setSize(300, 200);
addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
   System.exit(0);
      }
});
Container contentPane = getContentPane();
contentPane.add(new ButtonPanel());
}
}
public class java2{
public static void main(String[] args){
JFrame frame = new ButtonFrame();
frame.show();  
}
}

选项

答案第1处:jl.setForeground(color)第2处:jl.repaint()

解析 在构件类的方法中,setForeground()为设置构件的前景色,repaint()为重新绘制构件。
转载请注明原文地址:https://kaotiyun.com/show/36ID777K
0

相关试题推荐
最新回复(0)