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

generating IDs in Oracle with hibernate backed ORM
Struts2 Validation - Repopulate Children when validation fails
Looking for a Maven shortcut — including a jar file in a Maven build
How can I detect basic 2D geometric shapes (e.g. square, triangle, circle) on a JPEG image?
hibernate paging is resulting in select and update calls
Android Program wont start after name change
export flex datagrid to excel,which is better to implements with java or flex?
android locking eventListener and even handling
what approach should I take in heavy iterations? [closed]
Not able to Run Shell Script
How to persist SOAP Messages in MySQL Database - working with Axis Client
How does Application Server remove invalid or inactive sessions from storage?
Moving file to new location then deleting the Previous file
Vaadin portlet dynamic language change
Testing web pages using Java
In java, “5/0” statement doesn't fire SIGFPE signal on my Linux machine, why?

Categories

HOME
vim
wso2-am
netsuite
proxy
urbancode
reserved
dot
react-router
mean-stack
yahoo-oauth
filtering
yum
fancybox
slick-slider
dacpac
spring-xd
postgres-xl
orchardcms
circuit
django-cms
shared-hosting
alpine
dbext
clickonce
rundeck
angular2-aot
apache-commons-io
selectedindexchanged
nhapi
filezilla
minitab
jaxb2
gitignore
quote
tinymce-4
google-rich-snippets
contact-form
google-qpx-express-api
caret
http-referer
cloud-code
dynamics-crm-2013
code-search-engine
temporary-files
squib
awt
spring-security-kerberos
nxlog
estimote
total-commander
gpx
xml-documentation
jlink
sage-one
aurelia-validation
lowpass-filter
nodebb
memory-alignment
watchconnectivity
cubes
url-pattern
libpng
log4c
sts-springsourcetoolsuite
mongocsharpdriver
bstr
firebaseui
markojs
lua-5.1
ubuntu-10.04
ready-api
ipconfig
freelancer.com-api
freedesktop.org
google-places
intellij-14
feedback
coveralls
appfabric-cache
graph-drawing
census
angular-local-storage
notify
directoryservices
asp.net-web-api-odata
zend-route
has-many-through
transcoding
mcts
dir
jplaton
cos
pushbackinputstream
android-screen-support
jelly
cascalog
javaspaces
dbproviderfactories
django-tagging
pyinotify
sql-server-profiler
imac
mongomapper
yslow
coda-slider
gamequery
gamma
thunderbird-lightning
microsoft-virtualization
exchange-server-2003
uimenucontroller

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