java - 复选框不显示

标签 java checkbox constructor awt

我希望另一双眼睛可以帮助我找到我的代码错误的地方。我可以编译并运行该程序,但我得到的只是白屏。它应该显示复选框并将背景更改为选择的颜色。如有任何帮助,我们将不胜感激!

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

最佳答案

这不是构造函数:

public void Chapter5Debug()
{

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

<小时/>

在这一行

static Chapter5Debug f = new Chapter5Debug();

您正在调用默认构造函数,您拥有的 void 方法永远不会被调用。

关于java - 复选框不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17820264/

相关文章:

java - Spring Boot - JSP 未渲染

尝试从 API 获取 JSON 时,Java Spring 出现错误 404。从事 postman 工作

javascript - 如何在关闭模式后保留选中的复选框?

javascript - AngularJS 基于复选框选择显示数组

javascript - 如何使用JQuery获取表单中复选框的value属性?

java - 我应该改变流中的对象吗?

java - 错误 : stack depth limit exceeded - Java hibernate postgresql

templates - 模板化类中的构造函数继承 (C++11)

c# - 仅通过构造函数设置类的属性

c++ - 使用两个不同的构造函数初始化指向数组的指针