我最近刚学JAVA,写一个通过对话框来改变主窗口背景色的程序练手,但是遇到难题,就是我在对话框中无论怎么操作,主窗口的背景颜色就是不改变,到底怎么回事,请大家帮我看看。//主窗口
import java.awt.*;
import java.awt.event.*;public class ChangeColorDialong extends Frame implements ActionListener
{
    private ChangeColorDialong()
    {
        this.setLayout(new GridLayout(8,3));
        
        Button bt1 = new Button("变色");
        Button bt2 = new Button("退出");
        
        this.add(bt1);
        this.add(bt2);
        bt1.addActionListener(this);
        bt2.addActionListener(this);
        
        this.setSize(200,200);
        this.setVisible(true);
    }
    
    public void actionPerformed(ActionEvent e)
    {
        String str = e.getActionCommand();
        
        if(str.equals("变色"))
        {
            ConfirmDialong myDialog = new ConfirmDialong(); //ConfirmDialong是我自己写的一个对话框类,该类在下面给出
            
            if(myDialog.rbtStr.getText() == "黄色")         //我用过myDialog.rbtStr.getText().equals("黄色"),也不行            {
                this.setBackground(Color.yellow);
            }
            else if(myDialog.rbtStr.getText() == "绿色")
            {
                this.setBackground(Color.green);
            }
            else
            {
                this.setBackground(Color.white);
            }
        }
        else
        {
            System.exit(0);
        }
    }
    
    public static void main(String[] args) 
    {
        new ChangeColorDialong();
    }
}//我自己设计的对话框类
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;public class ConfirmDialong extends JDialog implements ItemListener
{
       private JRadioButton rbt1 = new JRadioButton("黄色");
       private JRadioButton rbt2 = new JRadioButton("绿色");
       private JRadioButton rbt3 = new JRadioButton("白色");
       public JRadioButton rbtStr;                            //改变量在下面用以捕获Item命令
       
       private class WindowCloser extends WindowAdapter
       {
              public void windowClosing(WindowEvent we)
              {
                    ConfirmDialong.this.setVisible(false);
              }
       }
       
       public ConfirmDialong()
       {
             this.setLayout(new GridLayout());
             add(rbt1);
             add(rbt2);
             add(rbt3);
             
             rbt1.addItemListener(this);
             rbt2.addItemListener(this);
             rbt3.addItemListener(this);
             
             this.setSize(200,100);
             this.setVisible(true);
       }
       
       public void itemStateChanged(ItemEvent e)
       {
           rbtStr = (JRadioButton)e.getItem();
       }
}

解决方案 »

  1.   

    GUI图形编程
    用工具自己生成代码吧
    这样写很乱if(myDialog.rbtStr.getText() == "黄色") 当你点变色的时候你没有设置它的初始颜色,到这一步出错,读不到颜色,后面的操作当然就没用了
      

  2.   


    我是为了了解GUI的原理所以才自己写代码的,不然拉拉控件就能实现摁钮的添加操作了,我当然也就没那么辛苦。但是也学不到什么东西。设置初始颜色?难道是在构造函数里面先给他设置一个初始颜色?
      

  3.   

    建议学GUI的时候不要使用拖拉控件的方式
    要写代码学习