java


Trying to draw a board


I have a paintComponent with if statements. In each case, the squares should be represented on the panel. Nothing is appearing.
#Override
public void paintComponent(Graphics g) {
//for loop to draw current board
for (int i = 0; i < rows; i++) {
for (int j = 0; j <= columns; j++) {
if (board[i][j] == '.') {
g.setColor(Color.black);
g.drawRect((xSize / 5) * i, (ySize / 6) * j, 50, 50);
}
if (board[i][j] == '#') {
g.setColor(Color.magenta);
g.drawRect((xSize / 5) * i, (ySize / 6) * j, 50, 50);
}
if (board[i][j] == '%') {
g.setColor(Color.orange);
g.drawRect((xSize / 5) * i, (ySize / 6) * j, 50, 50);
}
if (board[i][j] == '#') {
g.setColor(Color.pink);
g.drawRect((xSize / 5) * i, (ySize / 6) * j, 50, 50);
}
}
}
}//end of paint component
You have two issues,
You should not use magic numbers, use the variables that you have available.
g.fillRect(xSize * i, ySize * j, xSize, ySize);
Don't over-loop your columns. You should always use < because arrays are indexed starting at zero.
for (int j = 0; j < columns; j++) {
Working Example
import java.awt.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
private static final long serialVersionUID = 568117316148341762L;
private int columns;
private int rows;
private int xSize;
private int ySize;
private char[][] board;
public DrawPanel(int columns, int rows, int xSize, int ySize) {
super();
this.columns = columns;
this.rows = rows;
this.xSize = xSize;
this.ySize = ySize;
this.board = new char[rows][columns];
this.setPreferredSize(new Dimension(columns * xSize, rows * ySize));
setRandomTiles();
}
private void setRandomTiles() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = randTile();
}
}
}
private char randTile() {
switch ((int) (Math.random() * 4)) {
case 0: return '.';
case 1: return '#';
case 2: return '%';
case 3: return '#';
default: return ' ';
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// for loop to draw current board
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
switch (board[i][j]) {
case '.':
g.setColor(Color.BLACK);
break;
case '#':
g.setColor(Color.MAGENTA);
break;
case '%':
g.setColor(Color.ORANGE);
break;
case '#':
g.setColor(Color.PINK);
break;
}
g.fillRect(xSize * i, ySize * j, xSize, ySize);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Draw Panel");
DrawPanel p = new DrawPanel(30, 30, 10, 10);
f.setContentPane(p);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
}
You can load a board from a file using a BufferedReader.
import java.awt.*;
import java.io.BufferedReader;
import java.io.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
private static final long serialVersionUID = 568117316148341762L;
private int cols;
private int rows;
private int xSize;
private int ySize;
private char[][] board;
public DrawPanel(int rows, int cols, int xSize, int ySize) {
super();
this.rows = rows;
this.cols = cols;
this.xSize = xSize;
this.ySize = ySize;
this.board = new char[rows][cols];
init();
initRandomTiles();
}
public DrawPanel(String filename) {
super();
try {
loadBoard(filename);
init();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void init() {
this.setPreferredSize(new Dimension(cols * xSize, rows * ySize));
}
private void loadBoard(String filename) throws IOException {
InputStream is = this.getClass().getClassLoader().getResourceAsStream(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String[] metadata = br.readLine().split("\\s+");
this.rows = Integer.parseInt(metadata[0], 10);
this.cols = Integer.parseInt(metadata[1], 10);
this.xSize = Integer.parseInt(metadata[2], 10);
this.ySize = Integer.parseInt(metadata[3], 10);
this.board = new char[rows][cols];
int row = 0;
String line = null;
while ((line = br.readLine()) != null) {
board[row++] = line.trim().toCharArray();
}
}
private void initRandomTiles() {
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
board[row][col] = randTile();
}
}
}
private char randTile() {
switch ((int) (Math.random() * 4)) {
case 0: return '.';
case 1: return '#';
case 2: return '%';
case 3: return '#';
default: return ' ';
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
switch (board[row][col]) {
case '.':
g.setColor(Color.BLACK);
break;
case '#':
g.setColor(Color.MAGENTA);
break;
case '%':
g.setColor(Color.ORANGE);
break;
case '#':
g.setColor(Color.PINK);
break;
}
g.fillRect(xSize * col, ySize * row, xSize, ySize);
}
}
g.dispose();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame f = new JFrame("Draw Panel");
DrawPanel p = new DrawPanel("resources/board.txt");
f.setContentPane(p);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
});
}
}
board.txt
13 19 10 10
...................
.%#######%#######%.
.#...............#.
.#...............#.
.#...............#.
.#...............#.
.%...............%.
.#...............#.
.#...............#.
.#...............#.
.#...............#.
.%#######%#######%.
...................

Related Links

Collision Detection between a moving and non-moving object
Eclipse doesnt generate MainActivity,Layout xml and the launcer icon which is under drawable-ldpi folder
run bower install on heroku within a java/play project
pause and resume timer without reseting the timer
explanation for real-time behavior [closed]
Generate proxy classes for Java 1.4
JCifs login failure on windows to linux file transfer
How combine two strings with random position android
The correct way to make a GWT (Ajax) URL crawlable/indexable
Why byte and short values are promoted to int when an expression is evaluated [duplicate]
Java Swing: Controlling focus with textfield and autocompletion dialog/menu
jtable of characters in Java
My record is not inserting into database?
Unmappable character for encoding Cp1252 when trying to compile Java program
Disable JAXB NameSpace ns1 [duplicate]
Generics with polymorphism and factory class

Categories

HOME
java
arduino-uno
vim
debugging
image-processing
json.net
sd-card
at-command
maven-3
sharepoint-designer
rubygems
pivotal-cloud-foundry
add
synchronization
python-unittest
imacros
vb.net-2010
task
ibm-odm
clojurescript
foselasticabundle
database-replication
oxyplot
samoa
alpine
ml
riot.js
devops
crosstab
cas
django-storage
elasticsearch-ruby
saas
delicious-api
oracle-fusion-middleware
ioio
usbserial
caret
hybridauth
accelerate-framework
bower-install
simplexml
git-merge
theano.scan
leading-zero
awt
nand2tetris
isbn
import-from-excel
slick-3.0
angular2-meteor
executenonquery
osx-mavericks
azure-application-gateway
nativeapplication
dynamics-sl
orthogonal
paypal-express
actionbardrawertoggle
ipconfig
ptrace
independentsoft
phpcas
srand
intel-fortran
thredds
cyclomatic-complexity
arcanist
interrupted-exception
pretty-print
apache-commons-net
lustre
directoryservices
nsmutabledictionary
fscommand
nstableviewcell
ccss
tidy
buster.js
sabredav
android-hardware
cassini-dev
venn-diagram
zpt
rfc1123
table-footer
netbeans-7.1
ecl
gdlib
thunderbird-lightning
backcolor
commodore
lzh

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App