Applets are officially deprecated - it's time to stop using them - besides, Applet
s don't have a main
method.
Clearly have a lack of understanding into how painting works in AWT/Swing as you're about to run head long into a NullPointerException
. Stop what you're doing and start by reading through Performing Custom Painting and Painting in AWT and Swing
public static void main
is a static
context, meaning it can not reference non-static (or instance) fields and methods. Have a look at Understanding Class Members and Static methods vs Instance methods in Java for more details.
Remember, static
is not your friend, use it sparingly and wisely.
Instead of trying to fix your code directly, because Applet
is dead, I've provided a simple example of how painting should be done...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
drawCheckerboard(100, 100, g2d);
g2d.dispose();
}
protected void drawCheckerboard(int x, int y, Graphics2D g) {
int row;
int col;
for (row = 0; row < 8; row++) {
for (col = 0; col < 8; col++) {
x = col * 20;
y = row * 20;
if ((row % 2) == (col % 2)) {
g.setColor(Color.white);
} else {
g.setColor(Color.black);
g.fillRect(x, y, 20, 20);
}
}
}
}
}
}
Now, there are also two issues with your painting routine. The first, it's not actually using the x
/y
parameters passed to it, so both boards are getting painted to the same location. Second, it's ignoring the white
cell.
You can fix this simply enough...
protected void drawCheckerboard(int x, int y, Graphics2D g) {
int row;
int col;
for (row = 0; row < 8; row++) {
for (col = 0; col < 8; col++) {
int xPos = col * 20;
int yPos = row * 20;
if ((row % 2) == (col % 2)) {
g.setColor(Color.white);
} else {
g.setColor(Color.black);
}
g.fillRect(x + xPos, y + yPos, 20, 20);
}
}
}
Also, you'll need to change the getPreferredSize
to accomodate the content...
@Override
public Dimension getPreferredSize() {
return new Dimension(280, 660);
}