Думаю тут элементарная проблема и код не нужен. Я создаю массив интов в конструкторе класса, который является полем этого класса. private int[] prices;
В конструкторе объявляю через:
this.prices = new int[]{1,2,3,4,5};
. Потом через цикл вывожу эти элементы в консоль - выводятся.
Есть элементарный геттер этого массива. Потом у объекта этого класса через геттер я беру этот массив и запрашиваю его длину tour.getPrices().length;
, но вдруг вылетает nullpointerException. Я думал такие ошибки не будут вылетать при использовании примитивных типов.
Наверняка я что-то недогоняю в инициализации, но навряд ли. Может вы подскажете?
UPDATE: Предоставляю код. Класс, где хранятся массивы:
public class Tour {
private String depPoint, arrPoint;
private float price = 0;
private Image[] images;
private int[] prices;
private int rating = 2;
private Image img0, img1, img2, img3, img4, img5;
private boolean isHotel = false;
private int id;
public int getId() {
return id;
}public void setId(int id) {
this.id = id;
}
public String getDepPoint() {
return depPoint;
}
public void setDepPoint(String depPoint) {
this.depPoint = depPoint;
}
public String getArrPoint() {
return arrPoint;
}
public void setArrPoint(String arrPoint) {
this.arrPoint = arrPoint;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Image[] getImages() {
return images;
}
public void setImages(String[] names) {
/* images = new Image[names.length];
for (int i = 0; i < names.length; i++) {
Image img = null;
try {
img = ImageIO.read(new File("src/com/company/assets/" + names[i]));
} catch (IOException e) {
e.printStackTrace();
}
images[i] = img;
}*/
}
public int[] getPrices() {
return prices;
}
public void setPrices(int[] prices) {
this.prices = prices;
}
public int getRating() {
return rating;
}
public void setRating(int rate){
this.rating = rate;
}
public void setHotel(){
if(!isHotel){
price += 20000;
isHotel = true;
}
}
public void disposeHotel() {
if(isHotel) {
price -= 20000;
isHotel = false;
}
}
public boolean isHotel() {return isHotel;}
Tour(String depPoint, String arrPoint, Image[] images, int[] prices, int price, int rating, int id){
this.depPoint = depPoint;
this.arrPoint = arrPoint;
try {
img0 = ImageIO.read(new File("src/com/company/assets/rating0.png"));
img1 = ImageIO.read(new File("src/com/company/assets/rating1.png"));
img2 = ImageIO.read(new File("src/com/company/assets/rating2.png"));
img3 = ImageIO.read(new File("src/com/company/assets/rating3.png"));
img4 = ImageIO.read(new File("src/com/company/assets/rating4.png"));
img5 = ImageIO.read(new File("src/com/company/assets/rating5.png"));
this.images = new Image[]{img0, img1, img2, img3, img4, img5};
} catch (IOException e) {
e.printStackTrace();
}
this.prices = new int[]{50000,30000,100000,40000};
this.price = price;
this.rating = rating;
this.id = id;
}
@Override
public String toString() {
return "Город отправления:" + depPoint + "\tГород прибытия: " + arrPoint + "\nСтоимость: " + price + "\n\n";
}
}
Класс, где я работаю с объектом, в полях которого массивы:
public class TourFrame extends JFrame {
private JLabel picture, departureLabel, arrivalLabel, priceLabel, depDateLabel, arrDateLabel, ratingLabel, reviewsLabel;
private JDateChooser depDateChooser, arrDateChooser;
private JButton addToCartButton, leftButton, rightButton, graphicButton;
private JCheckBox hotelCheckBox;
private String depPoint, arrPoint;
private float price = 0;
private Image[] images;
private JPanel picturePanel, arrDateChooserPanel, depDateChooserPanel, ratingPanel, ratingPicturePanel, mainPicturePanel, depArrLabelsPanel, depArrChoosersPanel, hotelPriceButtonPanel, ratingGraphicPanel, reviewPanel;
private JScrollPane reviewsScrollPane;
private JTextArea reviewsTextArea;
private Tour tour;
private TourPanel parent;
private PicturePanel[] picturePanels;
TourFrame(Tour _tour, TourPanel _parent) {
tour = _tour;
parent = _parent;
if (parent.getHotelCheckBox().isSelected()) tour.setHotel();
init();
leftButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) picturePanel.getLayout();
layout.previous(picturePanel);
}
});
rightButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) picturePanel.getLayout();
layout.next(picturePanel);
}
});
addWindowListener(new WindowListener() {
@Override
public void windowOpened(WindowEvent e) { }
@Override
public void windowClosing(WindowEvent e) {
parent.closeFrame();
}
@Override
public void windowClosed(WindowEvent e) { }
@Override
public void windowIconified(WindowEvent e) { }
@Override
public void windowDeiconified(WindowEvent e) { }
@Override
public void windowActivated(WindowEvent e) { }
@Override
public void windowDeactivated(WindowEvent e) { }
});
setVisible(true);
}
public void init() {
setLayout(new GridLayout(3,2));
setTitle("Относительно подробная информация");
picturePanel = new JPanel(new CardLayout());
//PicturePanel[] picturePanels;
System.out.println(tour.getImages().length); // ТУТ ВСЕ РАБОТАЕТ ИДЕАЛЬНО.
if (tour.getImages() != null) {
picturePanels = new PicturePanel[tour.getImages().length];
for (int i = 0; i < tour.getImages().length; i++) {
picturePanels[i] = new PicturePanel(tour.getImages()[i], picturePanel);
picturePanel.add("pic0" + (i + 1) + " ", picturePanels[i]);
}
}
leftButton = new javax.swing.JButton();
rightButton = new javax.swing.JButton();
departureLabel = new javax.swing.JLabel();
arrivalLabel = new javax.swing.JLabel();
depDateLabel = new javax.swing.JLabel();
arrDateLabel = new javax.swing.JLabel();
depDateChooserPanel = new javax.swing.JPanel();
arrDateChooserPanel = new javax.swing.JPanel();
if (parent.getHotelCheckBox().isSelected()) hotelCheckBox = new javax.swing.JCheckBox("", true);
else hotelCheckBox = new javax.swing.JCheckBox("", false);
hotelCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(hotelCheckBox.isSelected()) tour.setHotel();
else tour.disposeHotel();
priceLabel.setText("Итоговая стоимость: " + tour.getPrice());
}
});
priceLabel = new javax.swing.JLabel();
addToCartButton = new javax.swing.JButton();
ratingPanel = new javax.swing.JPanel();
ratingLabel = new javax.swing.JLabel();
ratingPicturePanel = new RatingPicturePanel(tour.getRating());
reviewsLabel = new javax.swing.JLabel();
reviewsTextArea = new javax.swing.JTextArea();
reviewsScrollPane = new javax.swing.JScrollPane(reviewsTextArea);
graphicButton = new JButton();
arrDateChooser = new JDateChooser();
depDateChooser = new JDateChooser();
graphicButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(tour.getPrices() == null) System.out.println("null");
System.out.println(tour.getPrices().length); // ТУТ УЖЕ НЕ РАБОТАЕТ.
new GraphicDialog(TourFrame.this, tour);
}
});
addToCartButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parent.checkValid(parent);
}
});
reviewsTextArea.setEditable(false);
Font font = reviewsTextArea.getFont();
reviewsTextArea.setFont(font.deriveFont(font.getSize() + 3.5f));
updateReview();
reviewsTextArea.setLineWrap(true);
setSize(1053, 709);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
leftButton.setText("<-");
rightButton.setText("->");
departureLabel.setText("Город отправления: " + tour.getDepPoint());
arrivalLabel.setText("Город прибытия: " + tour.getArrPoint());
depDateLabel.setText("Дата отправления");
arrDateLabel.setText("Дата прибытия");
hotelCheckBox.setText("Отель");
priceLabel.setText("Итоговая стоимость: " + tour.getPrice());
addToCartButton.setText("Добавить в корзину");
ratingLabel.setText("Рейтинг");
reviewsLabel.setText("Отзывы");
reviewsTextArea.setColumns(20);
reviewsTextArea.setRows(5);
reviewsScrollPane.setViewportView(reviewsTextArea);
graphicButton.setText("График изменения цены");
mainPicturePanel = new JPanel(new BorderLayout());
mainPicturePanel.add(leftButton, BorderLayout.WEST);
mainPicturePanel.add(picturePanel, BorderLayout.CENTER);
mainPicturePanel.add(rightButton, BorderLayout.EAST);
depArrLabelsPanel = new JPanel(new GridLayout(1,2));
depArrLabelsPanel.add(departureLabel);
depArrLabelsPanel.add(arrivalLabel);
departureLabel.setAlignmentY(JComponent.CENTER_ALIGNMENT);
arrivalLabel.setAlignmentY(JComponent.CENTER_ALIGNMENT);
depArrChoosersPanel = new JPanel(new FlowLayout());
depDateChooserPanel.setLayout(new BoxLayout(depDateChooserPanel, BoxLayout.Y_AXIS));
arrDateChooserPanel.setLayout(new BoxLayout(arrDateChooserPanel, BoxLayout.Y_AXIS));
depDateChooserPanel.add(depDateLabel);
depDateChooserPanel.add(depDateChooser);
arrDateChooserPanel.add(arrDateLabel);
arrDateChooserPanel.add(arrDateChooser);
depArrChoosersPanel.add(depDateChooserPanel);
depArrChoosersPanel.add(arrDateChooserPanel);
hotelPriceButtonPanel = new JPanel();
hotelPriceButtonPanel.setLayout(new BoxLayout(hotelPriceButtonPanel, BoxLayout.PAGE_AXIS));
hotelPriceButtonPanel.add(hotelCheckBox);
hotelPriceButtonPanel.add(priceLabel);
hotelPriceButtonPanel.add(addToCartButton);
hotelCheckBox.setAlignmentX(JComponent.CENTER_ALIGNMENT);
priceLabel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
addToCartButton.setAlignmentX(JComponent.CENTER_ALIGNMENT);
ratingGraphicPanel = new JPanel(new BorderLayout());
ratingPanel.setLayout(new BoxLayout(ratingPanel, BoxLayout.Y_AXIS));
ratingPanel.add(ratingLabel);
ratingPanel.add(ratingPicturePanel);
ratingGraphicPanel.add(ratingPanel, BorderLayout.CENTER);
ratingGraphicPanel.add(graphicButton, BorderLayout.SOUTH);
reviewPanel = new JPanel();
reviewPanel.setLayout(new BorderLayout());
JPanel tempPanel = new JPanel();
tempPanel.add(reviewsLabel);
JButton reviewButton = new JButton("Добавить отзыв");
tempPanel.add(reviewButton);
reviewPanel.add(tempPanel, BorderLayout.NORTH);
reviewPanel.add(reviewsScrollPane, BorderLayout.CENTER);
reviewButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new ReviewDialog(TourFrame.this, tour);
}
});
add(mainPicturePanel);
add(depArrLabelsPanel);
add(depArrChoosersPanel);
add(hotelPriceButtonPanel);
add(ratingGraphicPanel);
add(reviewPanel);
}
public void updateReview(){
String msg = "";
for (int i = 0; i < Singleton.getCollection().getReviews().size(); i++) {
if (tour == Singleton.getCollection().getReview(i).getTour()) msg += Singleton.getCollection().getReview(i);
}
reviewsTextArea.setText(msg);
}
}