复选框已被选中

时间:2017-01-22 18:07:03

标签: java events checkbox awt

当用户点击CheckBox中的GUI个es之一时,我必须更改标签的字体。现在GUI可以正常工作但是当我单击一个复选框时,我在控制台中收到一条很长的错误消息并且文本没有改变。到目前为止,这是我的代码,希望你能帮助我:

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


public class FontP extends Frame{
    Label l1;
    Checkbox c1, c2, c3, c4;
    Panel p1, p2;
    CheckboxGroup cbg;

    FontP(String title) {
        super(title);
        ListenerB ab = new ListenerB();

        Panel p1 = new Panel();
        Panel p2 = new Panel();
        Label l1 = new Label("Some random text");
        CheckboxGroup cbg = new CheckboxGroup();
        Checkbox c1 = new Checkbox("Normal", cbg, false);
        c1.addItemListener(ab);
        Checkbox c2 = new Checkbox("Bold", cbg, false);
        c2.addItemListener(ab);
        Checkbox c3 = new Checkbox("Italic", cbg, false);
        c3.addItemListener(ab);
        Checkbox c4 = new Checkbox("Bold/Italic", cbg, false);
        c4.addItemListener(ab);

        p1.add(l1);
        p2.add(c1); p2.add(c2); p2.add(c3); p2.add(c4);

        add(p1,BorderLayout.NORTH);
        add(p2);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);

        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent ev) {
                    System.exit(0);
                }
        });       

    }

    class ListenerB implements ItemListener {
        public void itemStateChanged(ItemEvent ev) {
            if(c1.getState() == true) {
                Font f = new Font(l1.getText(), Font.PLAIN, 12);
                l1.setFont(f);                    
            }
            else if(c2.getState() == true) {
                Font f = new Font(l1.getText(), Font.BOLD, 12);
                l1.setFont(f);
            }
            else if(c3.getState() == true) {
                Font f = new Font(l1.getText(), Font.ITALIC, 12);
                l1.setFont(f);
            }
            else if(c4.getState() == true) {
                Font f = new Font(l1.getText(), Font.BOLD | Font.ITALIC, 12);
                l1.setFont(f);
            }      
        }
    }   
}

1 个答案:

答案 0 :(得分:0)

您没有在构造函数中初始化字段c1,c2,...但是定义新变量。因此字段c1,c2,...仍然为空,这会导致异常。在构造函数中执行此操作:

    p1 = new Panel();
    p2 = new Panel();
    l1 = new Label("Some random text");
    cbg = new CheckboxGroup();
    c1 = new Checkbox("Normal", cbg, false);
    c1.addItemListener(ab);
    c2 = new Checkbox("Bold", cbg, false);
    c2.addItemListener(ab);
    c3 = new Checkbox("Italic", cbg, false);
    c3.addItemListener(ab);
    c4 = new Checkbox("Bold/Italic", cbg, false);
    c4.addItemListener(ab);