-3

我不知道我是如何得到这个错误的。我做到了,所以当我点击时间按钮时,时间组合框变得可见。我的代码如下。我尝试了不同的方法,例如当单击按钮时,我插入时间面板,其中插入了组合框。我的代码不起作用的原因是什么?

 import javax.swing.JOptionPane;

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

public class events extends JFrame {
// variables for JPanel
private JPanel timePanel;
private JButton timeButton;
 private JButton moneyButton;
private JButton hotelButton;
private JButton exitButton;


 public events() 
 {




setLayout(new BorderLayout()); 

  JPanel buttonPanel = new JPanel();
  buttonPanel.setBackground(Color.RED);
  add(buttonPanel,BorderLayout.WEST);
  JPanel timePanel = new JPanel();
  timePanel.setBackground(Color.BLUE);
  timePanel.setPreferredSize(new Dimension(320, 240));

  add(timePanel,BorderLayout.EAST);   

   Time timeObject = new Time();
      timeObject.SelectTime();
      timePanel.add(timeObject.gettimePanel());
      timeObject.gettimePanel().setVisible(false);


  timeButton = new JButton("Time"); 
  buttonPanel.add(timeButton);

  moneyButton = new JButton("Price");
  buttonPanel.add(moneyButton);

  hotelButton = new JButton("Hotel");
  buttonPanel.add(hotelButton);

  exitButton = new JButton("Exit");
  buttonPanel.add(exitButton);


  buttontime clickTime = new buttontime();
  timeButton.addActionListener(clickTime);




   }

    //classes for Time
 public class buttontime implements ActionListener { //creating actionlistener for     clicking on timebutton to bring up a combobox
  public void actionPerformed(ActionEvent clickTime)  {
           Time timeObject = new Time();
      timeObject.SelectTime();
      timePanel.add(timeObject.gettimePanel());
      timeObject.gettimePanel().setVisible(true);


  }
  }






   public static void main (String args[]) {
events mainmenu = new events(); //object is created


mainmenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainmenu.setSize(600,400);
mainmenu.setVisible(true);
mainmenu.setLayout(new BorderLayout());
mainmenu.setTitle("Travel Agent System");
mainmenu.setBackground(Color.BLUE);

}





     import javax.swing.JOptionPane;

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

 class Time
{

  private JComboBox timeairportbox;//comboboxes declared
  private String[] Airport = {"","East Midlands", "Birmingham", "Manchester",  "Heathrow"};//array of airports declared


public void SelectTime() {



  //combobox objects created
  timeairportbox = new JComboBox(Airport);//array is inserted into the JComboBox
  timeairportbox.setVisible(false);   // Combobox is placed in the timePanel




 }

 public JComponent gettimePanel() {
    return timeairportbox;
    }

    }




}
4

1 回答 1

2

您在 的构造函数中隐藏变量,因此永远不会分配类成员变量,从而导致. 代替timePaneleventsNPE

JPanel timePanel = new JPanel();

timePanel = new JPanel();

另外: Java 命名约定表明类名以大写字母开头,这将使events Events.

于 2013-03-19T12:51:23.807 回答