Search code examples
javaswingjtextfieldjcheckboxitemlistener

Even if no errors on Compilation and Runtime, Program output is not as expected


A Java Swing applet which includes 3 Checkboxes and a TextField. The specified checkbox when clicked displays title assigned to the corresponding checkbox in the given TextField. The problem is that even if no errors on Compilation and Runtime, a blank frame is shown as output..!!

here is the Java code :

SwingAll class :

package swingall;

import java.awt.Container;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTextField;


public class SwingAll extends JFrame implements ItemListener {

JTextField t1;
JCheckBox c1,c2,c3;

public void init()
{
    Container cp=getContentPane();
    t1=new JTextField(20);
    c1=new JCheckBox("Arts");
    c2=new JCheckBox("Commerce");
    c3=new JCheckBox("Science");
    add(c1);
    add(c2);
    add(c3);
    add(t1);
    c1.addItemListener(this);
    c2.addItemListener(this);
    c3.addItemListener(this);
}

public void itemStateChanged(ItemEvent e) {

    if (e.getSource()==c1)
    {
        t1.setText("Arts");
    }
    if (e.getSource()==c2)
    {
        t1.setText("Commerce");
    }
    if (e.getSource()==c3)
    {
        t1.setText("Science");
    }
}
}

The Main Class is :

package swingall;

public class Main {

public static void main(String[] args) {

    SwingAll sg=new swingAll();
    sg.setSize(500, 500);
    sg.setVisible(true);
}
}

Solution

  • You never called your init() method.

    Therefore, you never put anything into the frame.