大家好,我在学习JAVA中遇到点问题想请教下大家。
    在Frame中不是继承了setBackground这个方法么,然后JFrame也继承了Frame,应该也有setBackground这个方法,为什么我编程时想通过按键就设置背景颜色,用JFrame是没有变化,然后换成Frame才有响应呢?
   附件有我那个程序的源代码。请大家帮下谢谢了。

解决方案 »

  1.   

    我修改了一下你的代码,能达到你的效果.要知道,用swing就得自己多做事,不能指望api都帮你做好
    import java.awt.*;
    import java.awt.event.*;import javax.swing.JFrame;class MyButton_test extends JFrame implements ActionListener
    { Button red = new Button("红色");
    Button green = new Button("绿色");
    Color color;
    MyButton_test()
    {
    add(red);
    add(green); red.addActionListener(this);
    green.addActionListener(this);
    setLayout(new FlowLayout());
    setVisible(true);
    setBounds(100, 100, 200, 200);
    color=Color.red;
    }
    public void actionPerformed(ActionEvent e)
    {

    if (e.getSource() == red)
    {
    color=Color.red;
    repaint();
    } else
    {
    color=Color.green;
    repaint();
    } }
    public void paint(Graphics g)
    {
    g.setColor(color);
    g.fillRect(0,0,this.getWidth(),this.getHeight());
    }
    public static void main(String[] args)
    {
    MyButton_test btn=new MyButton_test();
    btn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }}