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

Breadth First Neo4j tree traversal and TreeNode creation
Not able to run the PJSIP-JNI Wrapper on a standalone java application
Trying to add a JLabel, but it is stuck in the middle of Jframe
Play audio in sequence source from asset - Android
Reading the next line in a text file
How to write an int value to a file?
Failed to sign Mac OS X app
Android studio: debug application on device
How to get xml produced from jax-rs?
Change in windows height in two different browsers
merge equivalent classes using owl API
SSL in websockets in glassfish 4.0 Java EE7
Transpose a NxN matrix
SimpleDateFormat parse returns wrong value
Generating a large undirected weighted graph
What is the purpose of Defined Process in Service class of Manifest File in android?

Categories

HOME
asp.net-core
proxy
server
single-sign-on
office365api
session
at-command
filtering
react-redux
disassembler
opengl-es-2.0
datastax-java-driver
pheatmap
row
apache-cayenne
decomposition
iolanguage
uitypeeditor
saxon
plunker
ml
cx-freeze
ehcache
excel-2007
format-specifiers
crystal-reports-2010
opennlp
pepper
rst2pdf
minitab
xacml
stormpath
directx-10
airconsole
google-qpx-express-api
lxd
force-layout
az-application-insights
preconditions
ncalc
ruby-on-rails-3.1
nxlog
fakeiteasy
long-polling
menuitem
avconv
user-accounts
jedis
ionicons
blogengine.net
aurelia-validation
magma
nbconvert
titanium-android
gnome-shell-extensions
specrun
database-optimization
multi-level
impresspages
flash-cs5
oauth2client
teamcity-8.0
collapse
riak-cs
ionic
sankey-diagram
inmobi
kineticjs
knuth
coldbox
javafx-webengine
applescript-objc
starcluster
imdbpy
commoncrypto
cos
specification-pattern
anonymous-methods
runas
automount
online-compilation
ohm
spring-portlet-mvc
libc++
pydot
heartbeat
digest-authentication
wsdl.exe
.net-1.0

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