I want to create an applet with like 16 square tiles in it (square). Does anyone how I would be able to do this?
Printable View
I want to create an applet with like 16 square tiles in it (square). Does anyone how I would be able to do this?
Code:// <applet code="Sweet16" width="600" height="300"></applet>
import java.awt.*;
import java.awt.geom.Line2D;
import javax.swing.*;
public class Sweet16 extends JApplet {
int SIDE = 75;
int CELLS = 8;
public void init() {
setLayout(new GridLayout(1,0));
add(getTileComponent()); // component approach
add(new TilePanel(CELLS)); // graphic approach
}
private JPanel getTileComponent() {
JPanel panel = new JPanel(new GridLayout(CELLS,0));
Dimension size = new Dimension(SIDE, SIDE);
for(int i = 0; i < CELLS; i++) {
for(int j = 0; j < CELLS; j++) {
String s = String.valueOf(i*CELLS + j+1);
JLabel label = new JLabel(s, JLabel.CENTER);
label.setBorder(BorderFactory.createEtchedBorder());
label.setPreferredSize(size);
panel.add(label);
}
}
return panel;
}
}
class TilePanel extends JPanel {
int cells;
public TilePanel(int cells) {
this.cells = cells;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
double w = getWidth();
double h = getHeight();
double xInc = (w-1)/cells;
double yInc = (h-1)/cells;
g2.setPaint(Color.blue);
for(int i = 0; i <=cells; i++) {
double x = i*xInc;
g2.draw(new Line2D.Double(x, 0, x, h));
}
for(int i = 0; i <= cells; i++) {
double y = i*yInc;
g2.draw(new Line2D.Double(0, y, w, y));
}
for(int i = 0; i < cells; i++) {
float y = (float)(i*yInc + yInc*2/3);
for(int j = 0; j < cells; j++) {
String s = String.valueOf(i*cells + j+1);
float x = (float)(j*xInc + xInc/3);
g2.drawString(s, x, y);
}
}
}
}