0

As it shows on my code, I'm trying to make a simple JApplet with two JButtons and a JTextfield (which I haven't gotten to). Whenever I place everything on a container, I get a NullPointerException error. When I put it all on a JFrame, it works. I've made simple JApplets without placing all my components onto a JFrame before and they've worked but I can't seem to figure out why this one doesn't.

import javax.swing.*;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

public class ActionListenerPractice extends JApplet implements ActionListener
{

    Container con;
    //JFrame frame;
    JPanel panel;
    JButton dogButton, catButton;
    JTextField descriptionField;

    public static void main(String[] args)
    {
        new ActionListenerPractice();
    }

    public ActionListenerPractice()
    {
        init();
    }

    public void init()
    {/*
        //Create frame obj and set it
        frame = new JFrame();
        frame.setVisible(true);
        frame.setSize(500, 500);*/

        //Create panel obj and set it
        panel = new JPanel();
        panel.setLayout(new GridLayout(1,3));
        panel.setBackground(Color.black);

        //Add and set buttons
        dogButton = new JButton("I choose a dog");
        dogButton.addActionListener(this);
        dogButton.setBackground(Color.cyan);

        catButton = new JButton("I choose a cat");
        catButton.addActionListener(this);
        catButton.setBackground(Color.pink);

        //Add buttons to panel
        panel.add(dogButton);
        panel.add(catButton);

        //Add panel to container
        con.add(panel); 

        //frame.add(panel);

    }

    public void actionPerformed(ActionEvent e) 
    {
        if(e.getSource() instanceof JButton)
        {
            if(e.getSource() == dogButton)
            {
                JOptionPane.showMessageDialog(null,"You want to adopt a dog");
            }
            else if(e.getSource() == catButton)
            {
                JOptionPane.showMessageDialog(null, "You want to adopt a cat");
            }
        }

    }

}
Jonny Henly
  • 4,023
  • 4
  • 26
  • 43
Abigail Lo
  • 23
  • 1
  • 8

0 Answers0