点击一个按钮后,我得到一个NullPointerException
,我希望在屏幕上打印ArrayList
中的值。例如,如果我点击指向“A”的按钮,屏幕上将显示“A”,如果我点击指向“B”的按钮,屏幕上将显示“B”。
public class Media extends JPanel {
//Declares our media player component
private JPanel video_pnl, control_pnl;
private JButton play_btn;
private JLabel loc_lbl;
private int increment;
ArrayList<String> file_location;
public Media(ArrayList<String> file_location) {
this.file_location = file_location;
increment = 0;
while (increment < file_location.size()) {
video_pnl = new JPanel();
video_pnl.setLayout(new BoxLayout(video_pnl, BoxLayout.Y_AXIS));
loc_lbl = new JLabel();
loc_lbl.setText(file_location.get(increment));
play_btn = new JButton("Play");
control_pnl = new JPanel();
control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
play_btn.setActionCommand("play");
video_pnl.add(loc_lbl);
control_pnl.add(play_btn);
video_pnl.add(control_pnl, BorderLayout.SOUTH);
Handler handler = new Handler();
play_btn.addActionListener(handler);
video_pnl.revalidate();
add(video_pnl);
increment++;
}
}
private class Handler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("play")) {
play();
}
// if (e.getSource() == play_btn){
// play();
// }
}
}
public void play() {
for (int i = 0; i < file_location.size(); i++) {
System.out.println(file_location.get(i));
}
}
public static void main(String[] args) {
//Declare and initialize local variables
ArrayList<String> file_location = new ArrayList<>();
file_location.add("A");
file_location.add("B");
file_location.add("C");
file_location.add("D");
file_location.add("E");
//creates instances of the VlcPlayer object, pass the mediaPath and invokes the method "run"
Media mediaplayer = new Media(file_location);
JFrame ourframe = new JFrame();
ourframe.setContentPane(mediaplayer);
ourframe.setLayout(new GridLayout(5, 1));
ourframe.setSize(300, 560);
ourframe.setVisible(true);
ourframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
答案 0 :(得分:2)
添加:
this.file_location = file_location;
进入构造函数(在此行下:public Media(ArrayList file_location){)
答案 1 :(得分:0)
在构造函数中,您引用参数file_location
来构建面板,但是您从不将数组存储在类变量中。由于默认情况下它已初始化为null
,因此当您在play ()
方法中引用NPE时,会获得NPE。
使用参数的值(this.file_location = file_location
)在构造函数中初始化类成员,它将解决您的问题。
另外,我建议您使用尚未用于类成员的参数名称。如果您指的是参数或成员,那么在阅读代码时会更容易注意,并且可以防止您刚刚观察到的问题。