I want to create a 6 * 8 board thing using a JLabel array and GridBagLayout. I'm trying to add the gridbag components using a loop because I don't want to manually add 48 components to the board. I'm not sure if I did this correct or if the error lies elsewhere.
Here's my code:
public class Template {
private JFrame frame;
JPanel templatePanel;
JLabel[][] template = new JLabel[6][8];
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Template window = new Template();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Template() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
templatePanel = new JPanel();
templatePanel.setBackground(Color.WHITE);
frame.getContentPane().add(templatePanel, BorderLayout.CENTER);
GridBagLayout g = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
templatePanel.setLayout(g);
gbc.fill = GridBagConstraints.HORIZONTAL;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 8; j++) {
template[i][j].setText("_");
gbc.gridx = j;
gbc.gridy = i;
templatePanel.add(template[i][j], gbc);
}
}
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Here's the error message:
java.lang.NullPointerException: Cannot invoke "javax.swing.JLabel.setText(String)" because "this.template[i][j]" is null
at Template.initialize(Template.java:59)
at Template.<init>(Template.java:38)
at Template$1.run(Template.java:25)
at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:316)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)