When I try to start the swing timer using timer.start(); it just brings up a null pointer exception error that I have no idea how to fix. Am I calling it wrong? I've seen examples of it having the timer.start(); in the actual timer method but I don't know where to put it in my code. Any help would be appreciated!!!! Thank you.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Board extends JPanel {
private Timer timer;
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.fillRect(30, 30, 640, 640);//makes a black square
for(int i=30;i<=510; i+=160)//adds white columns
{
for(int j=30; j<=510; j+=160)
{
g.clearRect(i, j, 80, 80);
}
}
for(int i=110; i<=590; i+=160)//adds black columns
{
for(int j=110; j<=590; j+=160)
{
g.clearRect(i, j, 80, 80);
}
}
g.setFont(new Font("Monospace", Font.BOLD, 30));
g.setColor(Color.WHITE);
g.drawString("a", 85, 660);
g.drawString("c", 245, 660);
g.drawString("e", 405, 660);
g.drawString("g", 565, 660);
g.drawString("7", 35, 140);
g.drawString("5", 35, 300);
g.drawString("3", 35, 460);
g.drawString("1", 35, 620);
g.setColor(Color.BLACK);
g.drawString("b", 165, 660);
g.drawString("d", 325, 660);
g.drawString("f", 485, 660);
g.drawString("h", 645, 660);
g.drawString("8", 35, 60);
g.drawString("6", 35, 220);
g.drawString("4", 35, 380);
g.drawString("2", 35, 540);
timer.start();
}
public void showX(Graphics g)
{
g.setFont(new Font("wrongFont", Font.BOLD, 200));
g.setColor(Color.RED);
g.drawString("X", 35, 540);
}
public void boardImage()
{
JFrame frame=new JFrame();
frame.setSize(600, 600);
frame.getContentPane().add(new Board());
frame.setLocationRelativeTo(null);
frame.setBackground(Color.LIGHT_GRAY);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
CoordinateGame game=new CoordinateGame();
frame.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int x=e.getX();
int y=e.getY();
}
});
}
public static void Timer()
{
class TimerListener implements ActionListener
{
int elapsedSeconds = 30;
@Override
public void actionPerformed(ActionEvent evt)
{
Timer timer = new Timer(1000, new TimerListener());
elapsedSeconds--;
System.out.println(":(");
if(elapsedSeconds <= 0){
timer.stop();
}
}
}
}
}