当我将面板添加到容器中时,为什么我的代码不起作用但是当我使用JFrame时它可以工作?

时间:2016-04-11 22:51:09

标签: java swing jframe containers japplet

正如我在我的代码中所显示的那样,我正在尝试使用两个JApplet和一个JButtons制作一个简单的JTextfield(我还没有这样做)。每当我将所有内容放在容器上时,都会出现NullPointerException错误。当我把它全部放在JFrame上时,它就可以了。我做了简单的JApplets而没有将我的所有组件放到JFrame之前,他们已经工作但我似乎无法弄清楚为什么这个没有。

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");
            }
        }

    }

}

0 个答案:

没有答案