我有以下代码,并在此行获得NullPointerException:
Component storeAll[]=checkPanel.getComponents();
代码:
public class Scroll extends JFrame implements ActionListener {
private HashMap<JCheckBox, ArrayList<Integer>> map = new HashMap<>();
JPanel checkPanel;
private static int MAX_CHECKS = 100;
public Scroll() {
super();
setLayout(new BorderLayout());
JPanel checkPanel = new JPanel(new GridLayout(0, 1));
checkPanel.setLayout(new FlowLayout());
JCheckBox checkBox;
Random r = new Random();
for (int i = 0; i < MAX_CHECKS; i++) {
StringBuilder sb = new StringBuilder();
ArrayList<Integer> a = new ArrayList<>();
for (int j = 0; j < 2; j++) {
Integer temp = (r.nextInt()) % 100;
a.add(temp);
sb.append(temp).append(" ");
}
checkBox = new JCheckBox(sb.toString().trim());
checkBox.setName("CheckBox" + i);
map.put(checkBox, a);
checkPanel.add(checkBox);
}
add(checkPanel,BorderLayout.CENTER);
JButton startButton = new JButton("Start");
add(startButton, BorderLayout.SOUTH);
startButton.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 800);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
Component storeAll[]=checkPanel.getComponents();
for(Component c:storeAll){
if(((JCheckBox)c).isSelected())
{
checkPanel.remove(c);
checkPanel.revalidate();
validate();
repaint();
}
else
{
JOptionPane.showMessageDialog(this,"No button to remove");
}
}
}
public static void main(String[] args) {
Scroll asds = new Scroll();
}
}