2013-07-23 86 views
0

我希望另一组眼睛可以帮助我找到我的代码出错的地方。我可以编译和运行该程序,但我得到的只是一个白色屏幕。它应该显示复选框并将背景更改为选择的颜色。任何帮助表示赞赏!复选框未显示

import javax.swing.JOptionPane; 
import java.awt.*; 
import java.awt.event.*; 

public class Chapter5Debug extends Frame implements ItemListener 
{ 
static Chapter5Debug f = new Chapter5Debug(); 

CheckboxGroup options = new CheckboxGroup(); 
    Checkbox blue = new Checkbox("Blue",false,options); 
    Checkbox red = new Checkbox("Red",false,options); 
    Checkbox yellow = new Checkbox("Yellow",false,options); 
    Checkbox pink = new Checkbox("Pink",false,options); 
    Checkbox gray = new Checkbox("Gray",false,options); 


public void Chapter5Debug() 
{ 
    this.setLayout(new FlowLayout()); 
    add(blue); 
    add(red); 
    add(yellow); 
    add(pink); 
    add(gray); 
    blue.addItemListener(this); 
    red.addItemListener(this); 
    yellow.addItemListener(this); 
    pink.addItemListener(this); 
    gray.addItemListener(this); 

    //overriding windowClosing() allows user to click Close button 
    addWindowListener(
     new WindowAdapter() 
     { 
      public void windowClosing(WindowEvent e) 
      { 
       System.exit(0); 
      } 
     } 
    ); 

} //end of constructor method 

public static void main(String[] args) 
{ 
    //ColorButtons f = new ColorButtons(); 
    f.setBounds(200,200,500,100); 
    f.setTitle("What's My Color?"); 
    f.setVisible(true); 
} //end of main 

public void actionPerformed(ActionEvent e) 
{ 
    if (blue.getState()) f.setBackground(Color.blue); 
    else if (red.getState()) f.setBackground(Color.red); 
    else if (yellow.getState()) f.setBackground(Color.yellow); 
    else if (pink.getState()) f.setBackground(Color.pink); 
    else if (gray.getState()) f.setBackground(Color.gray); 
} //end of actionPerformed method 

public void itemStateChanged(ItemEvent e) 
{ 
} 

} //end of class 

回答

5

这不是一个构造函数:

public void Chapter5Debug() 
{ 

这是一个void方法。你想要一个构造函数?删除void关键字。


在这一行

static Chapter5Debug f = new Chapter5Debug(); 

你调用默认的构造函数,你有void方法不会被调用。

+3

您有敏锐的眼睛 – chancea

+0

谢谢。我删除了空白,可以看到颜色复选框,但背景仍然是白色的。欣赏你敏锐的眼睛:-) –

0

actionPerformed中有代码,但该类不是actionListener。

将该代码移动到选中复选框时执行的itemStateChanged。 您可能需要在更改背景颜色以显示更改后添加f.repaint()。