import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class test {

public static void main(String[] args) {
JFrame frame=new JFrame("Click the Button to change the Frame Blackground color");
frame.setSize(200,300);
JButton button=new JButton("Change");
frame.add(button);
button.addActionListener(new action());
frame.pack();
frame.setVisible(true);
}
}class action implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() instanceof JButton){
JButton jb=(JButton) e.getSource();
//如果当前窗口的背景颜色为红色,则为灰色,如果为灰色,则改为蓝色
//这段程序该如何实现.

}

}
}

解决方案 »

  1.   

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public class Test { public static void main(String[] args) {
    JFrame frame = new JFrame(
    "Click the Button to change the Frame Blackground color");
    frame.setSize(200, 300);
    JButton button = new JButton("Change");
    frame.setLayout(new FlowLayout());
    frame.add(button);
    button.addActionListener(new action(frame.getContentPane()));
    frame.pack();
    frame.setVisible(true);
    }
    }class action implements ActionListener {
    private Container con;
    public action(Container con){
    this.con = con;
    }


    public void actionPerformed(ActionEvent e) {
    if (e.getSource() instanceof JButton) {
    JButton jb = (JButton) e.getSource();
    if(con.getBackground() == Color.BLUE){
    con.setBackground(Color.yellow);
    return ;
    }
    con.setBackground(Color.blue);
    // 如果当前窗口的背景颜色为红色,则为灰色,如果为灰色,则改为蓝色
    // 这段程序该如何实现.
    } }
    }
      

  2.   

    to allen830826:
      可否说详细一些,我用递归了, 但是最后出异常了(avax.swing.JButton cannot be cast to javax.swing.JFrame);我的代码如下:
    Object ob= e.getSource();
    Object oo;
    if(ob instanceof JFrame){
    oo=ob;
    ob=((Component) oo).getParent();
    }
    JFrame myjf=(JFrame) ob;
    if(myjf.getBackground()==Color.GRAY)
    myjf.setBackground(Color.BLUE);
    else myjf.setBackground(Color.GRAY);to zla85:因为创建Button的时候,并不清楚当前窗口的对象叫什么,有没有其它的方法仅仅从JButton发出去的事件中获取其所有窗口的对象.
      

  3.   

    因为你的action 是一个新的类,所以为了Button能处理父窗口的背景颜色在action的构造函数里把父类对象传进来咯。我的思路是这样的,说实话,你的代码我看不懂什么意思....