正如我在我的代码中所显示的那样,我正在尝试使用两个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");
}
}
}
}