【问题标题】:JApplet will not initialize when Listener is added to jcheckBox将 Listener 添加到 jcheckBox 时,JApplet 不会初始化
【发布时间】:2015-10-22 05:28:18
【问题描述】:

好的,因为上次没有成功。我将在这里发布我的完整代码,我希望我能得到一些关于它为什么不起作用的回复。我没有收到任何编译错误,小程序运行,然后什么都没有显示,底部显示“小程序未初始化”。我正在使用blueJ。我为这篇文章的长度道歉,我不知道如何用更短的代码来犯同样的错误。

我有一个包含多个类的 JApplet 程序。 RegPanel、WorkshopPanel、ConferenceGUI、ConferenceHandler 和 ConferenceClient。基本上 RegPanel 和 WorkShop 面板被添加到 ConferenceGUI 中,它还创建并添加了几个小面板。 ConferenceClient 类只是用来启动类来运行小程序。 ConferenceHandler 用于处理 JButtons、JTextArea、JCheckBox 等的动作事件……通常整个程序都可以正常工作。除非我为 JCheckBox 添加侦听器,否则它会停止工作。问题区域在 ConferenceGUI 类中,用星号注释以清楚导致问题的原因。

我已经被这个错误困住了大约一天了,我感到非常沮丧。所以,为了重点,这里是完整的代码: (拜托,我不需要任何其他代码部分的提示,我只需要有关该错误的帮助)。您可能想跳过代码,只阅读错误所在的 ConferenceGUI 类。如果您还可以向我解释为什么这不起作用,那将对我非常有帮助。提前谢谢!

RegPanel 类:

import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class RegPanel extends JPanel
{
    protected JTextField regNameTextBox;

    protected JCheckBox keynoteCheckBox;

    protected final String[] REGTYPES = {"Please select a   type","Business","Student","Complimentary"};
    protected JPanel registrationPanel, keynotePanel;
    protected final double BUSINESSFEE = 895,STUDENTFEE = 495,COMPLIMENTARYFEE = 0;
    protected JComboBox regTypeComboBox;
    public RegPanel()
    {
        //Set the layout for the RegPanel to be 2 rows and 1 column.
        setLayout(new GridLayout(2, 1));

        //initiate the registration panel and add a border
        registrationPanel = new JPanel();
        registrationPanel.setLayout(new FlowLayout());
        registrationPanel.setBorder(BorderFactory.createTitledBorder("Registrant's Name & Type"));


        //initiate the comboBox and add the registration types
        regTypeComboBox = new JComboBox(REGTYPES);

        //Initiate the textfield with a size of 20
        regNameTextBox = new JTextField(20);

        //Add the registration name textbox and type combobox to the registration panel
        registrationPanel.add(regNameTextBox);
        registrationPanel.add(regTypeComboBox);

        //initiate the second panel for the checkbox
        keynotePanel = new JPanel();
        keynotePanel.setLayout(new FlowLayout());

        //initiate the checkbox and add it to the keynote panel
        JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
        keynotePanel.add(keynoteCheckBox);

        //Add the two panels to the main panel
        add(registrationPanel);
        add(keynotePanel);

    }    
    public double getRegistrationCost()
    {
        double regFee = 0;
        String comboBoxAnswer = (String)regTypeComboBox.getSelectedItem();

        switch (comboBoxAnswer)
            {
                case "Business": regFee = BUSINESSFEE;
                   break;
                case "Student": regFee = STUDENTFEE;
                    break;

            }
        return regFee;    
    }        
    public double getKeynoteCost()
    {
        double keynoteCost = 0;
        if(keynoteCheckBox.isSelected())
        {
            keynoteCost = 30;
        }    
        return keynoteCost;
    }
    public String getRegType()
    {
        String regType = (String)regTypeComboBox.getSelectedItem();
        return regType;
    }    
}

WorkshopPanel 类:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class WorkshopPanel extends JPanel
{
    protected final double ITFEE = 295, DREAMFEE = 295, JAVAFEE = 395, ETHICSFEE = 395;
    protected final String[] WORKSHOPS = {"IT Trends in Manitoba","Creating a Dream Career","Advanced Java Programming","Ethics: The Challenge Continues"};
    protected JList workshopList;
    public WorkshopPanel()
    {
        setLayout(new FlowLayout());

        workshopList = new JList(WORKSHOPS);
        workshopList.setSelectionMode(2);


        BorderFactory.createTitledBorder("Workshops");

        add(workshopList);
    }    

    public double getWorkshopCost()
    {
        Object[] workshops = workshopList.getSelectedValues();
        double cost = 0;
        String workshopString;
        for (int i = 0; i < workshops.length; i++)
        {
          workshopString = (String)workshops[i];
          switch(workshopString)
          {
              case "IT Trends in Manitoba":
                cost += ITFEE;
                break;
              case "Creating a Dream Career":  
                cost += DREAMFEE;
                break;
              case "Advanced Java Programming":
                cost += JAVAFEE;
                break;
              case "Ethics: The Challenge Continues":
                cost += ETHICSFEE;
                break;

        }    
    }    
        return cost;

    }
    public Object[] getWorkshopList()
    {
        Object[] workshopListArray = workshopList.getSelectedValues();
        return workshopListArray;
    }    
}    

ConferenceGUI 类(这包含错误):

import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceGUI extends JPanel
{
   protected JPanel titlePanel, buttonPanel;
   protected RegPanel regPanel;
   protected WorkshopPanel workshopPanel;
   protected JLabel titleLabel;
   protected JButton calculateButton, clearButton;
   protected JTextArea resultArea;
   protected JScrollPane textScroll;


   public ConferenceGUI()
   {



       setLayout(new BorderLayout());

       titlePanel = new JPanel();

       titleLabel = new JLabel("Select Registration Options",JLabel.CENTER);

       Font titleFont = new Font("SansSerif", Font.BOLD, 18);

       titleLabel.setFont(titleFont);

       titlePanel.add(titleLabel);

       add(titlePanel, BorderLayout.NORTH);

       regPanel = new RegPanel();
       add(regPanel, BorderLayout.WEST);


       workshopPanel = new WorkshopPanel();
       add(workshopPanel, BorderLayout.EAST);

       buildButtonPanel();
       add(buttonPanel, BorderLayout.SOUTH);


       ConferenceHandler handler = new ConferenceHandler(this);

       regPanel.regTypeComboBox.addItemListener(handler);
       regPanel.regNameTextBox.addFocusListener(handler);
       //****************************************************************
       //The line below is what causes the error. Without it the code
       //Works, with it it doesn't and i get the aforementioned error.  


       //regPanel.keynoteCheckBox.addItemListener(handler);




   }    
   private void buildButtonPanel()
   {
       buttonPanel = new JPanel();
       buttonPanel.setLayout(new FlowLayout());

       calculateButton = new JButton("Calculate Charges");
       buttonPanel.add(calculateButton);

       clearButton = new JButton("Clear");
       buttonPanel.add(clearButton);


       resultArea = new JTextArea(5,30);
       textScroll = new JScrollPane(resultArea);

       buttonPanel.add(textScroll);

       ConferenceHandler handler = new ConferenceHandler(this);
       calculateButton.addActionListener(handler);
       clearButton.addActionListener(handler);

   }    
}

ConferenceHandler 类(这个类是未完成的,直到我解决了那个错误):

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class ConferenceHandler implements ActionListener, ItemListener, FocusListener
{
    protected ConferenceGUI gui;
    public ConferenceHandler(ConferenceGUI gui)
    {
        this.gui = gui;
    }    
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == gui.calculateButton)
        {
           String regType = gui.regPanel.getRegType();
           Object[] workshopList = gui.workshopPanel.getWorkshopList();

           String workshopString;




           if (regType == "Please select a type")
           {
               JOptionPane.showMessageDialog(null,"Please select a registration type","Type Error",JOptionPane.ERROR_MESSAGE );
           }    
           else
           {
               if(gui.regPanel.keynoteCheckBox.isSelected())

               {  
                   gui.resultArea.append("Keynote address will be attended/n");
               } 
               else
               {
                   gui.resultArea.append("Keynot address will not be attended/n");
               }    

           }
        }
        if (e.getSource() == gui.clearButton)
        {
            gui.resultArea.append("CLEAR");
        }    
    }
    private double getTotalCharges()
    {
        double charges = 0;



        return charges;
    }    
    public void itemStateChanged(ItemEvent e)
    {
    }
    public void focusLost(FocusEvent e)
    {
    }
    public void focusGained(FocusEvent e)
    {
    }    

}

ConferenceClient 类:

import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceClient extends JApplet
{
  private final int WINDOW_HEIGHT = 700, WINDOW_WIDTH = 250; 
  private ConferenceGUI gui;

  private Container c;

  public ConferenceClient()
  {
      gui = new ConferenceGUI();

      c = getContentPane();

      c.setLayout(new BorderLayout());

      c.add(gui, BorderLayout.CENTER);

      setSize(WINDOW_HEIGHT, WINDOW_WIDTH);
  }    
}

【问题讨论】:

  • This: regType == "Please select a type" 不是如何在 Java 中比较 Strings,您想使用更像 "Please select a type".equals(regType) 的东西

标签: java listener japplet bluej jcheckbox


【解决方案1】:

您正在隐藏您的 keynoteCheckBox 变量。首先你在RegPanel中创建了一个实例字段,但是在构造函数中,你重新声明了它...

public class RegPanel extends JPanel {

    protected JCheckBox keynoteCheckBox;
    //...

    public RegPanel() {
        //...
        //initiate the checkbox and add it to the keynote panel
        JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
        keynotePanel.add(keynoteCheckBox);

这会将实例字段保留为null,这将导致NullPointerException

另外,这个:regType == "Please select a type" 不是如何在 Java 中比较 Strings,你想使用更像 "Please select a type".equals(regType) 的东西

【讨论】:

  • 非常感谢!我花了很多时间梳理相同的代码块,但一直忽略了这一点。
  • @StanHarris,如果你的问题解决了,那么不要忘记点击复选标记“接受”答案。您已经提出了 14 个问题,但没有一次接受过答案。
猜你喜欢
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
相关资源
最近更新 更多