Java panel/frame graphic not working - java

I am trying to make a game of life simulation using Java Graphics but when a run my code the left one third of the screen is grey.I want the whole screen to be white with black squares representing living squares. I am confused about all the java containers/panels and frames.
Here's my code:
public class ConwayGame {
static JPanel panel;
static JFrame frame;
public static void main(String[] args) throws InterruptedException{
int [][] array = new int [40][40];
/*
* Set the pattern for Conway's Game of Life by manipulating the array below.
*/
/*Acorn
*/
array[19][15]=1;
array[19][16]=1;
array[19][19]=1;
array[19][20]=1;
array[19][21]=1;
array[18][18]=1;
array[17][16]=1;
panel = new JPanel();
Dimension dim = new Dimension(400, 400);
panel.setPreferredSize(dim);
frame = new JFrame();
frame.setSize(400,400 );
Container contentPane = frame.getContentPane();
contentPane.add(panel);
frame.setVisible(true);
/*
* Runs the Game of Life simulation "a" number of times.
*/
Graphics g = panel.getGraphics();
drawArray(array, g);
//paint(g);
//Thread.sleep(125);
//g.dispose();
}
/*
* Creates the graphic for Conway's game of life.
*/
public static void drawArray(int[][] array, Graphics g) {
int BOX_DIM = 10;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
g.drawRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
if (array[i][j] == 0) {
g.setColor(Color.WHITE);
g.fillRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
}
if (array[i][j] == 1) {
g.setColor(Color.BLACK);
g.fillRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
}
}
}
}
}
Here's a picture of what is generated:

DON'T use Graphics g = panel.getGraphics(); EVER. This is not how custom painting works in Swing. Take a look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works
For example...
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ConwayGame {
static JPanel panel;
static JFrame frame;
public static void main(String[] args) throws InterruptedException {
int[][] array = new int[40][40];
array[19][15] = 1;
array[19][16] = 1;
array[19][19] = 1;
array[19][20] = 1;
array[19][21] = 1;
array[18][18] = 1;
array[17][16] = 1;
panel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawArray(array, g);
}
};
frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
/*
* Creates the graphic for Conway's game of life.
*/
public static void drawArray(int[][] array, Graphics g) {
int BOX_DIM = 10;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
g.drawRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
if (array[i][j] == 0) {
g.setColor(Color.WHITE);
g.fillRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
}
if (array[i][j] == 1) {
g.setColor(Color.BLACK);
g.fillRect(i * BOX_DIM, j * BOX_DIM, 10, 10);
}
}
}
}
}
Now, personally, I would create a custom component, which extended from JPanel and would place all the logic you needed into that class

Related

2D array grid - placing character in the middle of each cell

having a 2d array of characters that is supposed to represent a map
char test[][]={{'A','B','C'},{'D','E','F'},{'G','H','I'};
how would I create a 3x3 grid using the java.awt library that has each character at the center of each cell?
The code below gives me a a grid but I am still not sure how to put each character at the center of each cell.
int sideLength=115;
int distance=sideLength*3;
int i=0;
int j=0;
for ( int x=90; x<=distance; x+=sideLength )
{
for( int y=30; y<=distance; y+=sideLength )
{
g.drawRect(x,y,sideLength, sideLength);
g.drawString(Character.toString(test[i][j]), sideLength/2, sideLength/2);
}
i++;
j++;
}
This code gives me this output
Nothing but smoke and mirrors...
Okay, JLabels and Borders
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridLayout(0, 3));
String test[][]={{"A","B","C"},{"D","E","F"},{"G","H","I"}};
Border paddingBorder = new EmptyBorder(50, 50, 50, 50);
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
JLabel label = new JLabel(test[row][col]);
label.setVerticalAlignment(JLabel.CENTER);
label.setHorizontalAlignment(JLabel.CENTER);
Border edgeBorder = new MatteBorder(
1,
1,
row == 2 ? 1 : 0,
col == 2 ? 1 : 0,
Color.BLACK);
label.setBorder(new CompoundBorder(edgeBorder, paddingBorder));
add(label);
}
}
}
}
}
There's lots of variations on this subject, but it represents the simplest approach
Custom Paint Route...
If, you want to follow a custom paint route, then you're going to need to have a better understanding of how fonts actually work.
I would recommend starting with Working with Text APIs to gain a basic understanding.
Next, you're incrementing your i and j properties correctly. j needs to be reset before you render each column and should increment for each row.
Personally, I'd do it the other way round, where you used the index for each row/column to get the value from the array and then calculate the x/y position based on the current row/column index, but that's just me.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
String test[][] = {{"A", "B", "C"}, {"D", "E", "F"}, {"G", "H", "I"}};
public TestPane() {
}
#Override
public Dimension getPreferredSize() {
return new Dimension(90 + (115 * 4), 30 + (115 * 4));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int sideLength = 115;
int distance = sideLength * 3;
int i = 0;
for (int x = 90; x <= distance; x += sideLength) {
int j = 0;
for (int y = 30; y <= distance; y += sideLength) {
g.drawRect(x, y, sideLength, sideLength);
FontMetrics fm = g.getFontMetrics();
int yPos = y + ((sideLength - fm.getHeight()) / 2) + fm.getAscent();
int xPos = x + ((sideLength - fm.stringWidth(test[i][j])) / 2);
g.drawString(test[i][j], xPos, yPos);
j++;
}
i++;
}
}
}
}
You're close, but I would refactor your loops slightly. Instead of iterating on distance, iterate on the index in the array. Use the array index to then derive the positions.
char[][] test = {{'A','B','C'}, {'D','E','F'}, {'G','H','I'}};
int sideLength=115;
for (int i = 0; i < test.length; i++) {
int x = 90 + sideLength * i;
for (int j = 0; j < test[j].length; j++) {
int y = 30 + sideLength * j;
g.drawRect(x, y, sideLength, sideLength);
g.drawString(
Character.toString(test[i][j]),
x + sideLength / 2,
y + sideLength / 2);
}
}

Why are JLabels being painted over higher components in a JLayeredPane?

I have a JLayeredPane that has four layers:
JPanel set as a background
Grid of JPanels each holding a JLabel
Grid of JPanels each holding several JLabels that are only set to visible if the label in the panel below is empty
A custom component that is only used to override the paintComponent() method to draw over everything below
For some reason if I change the background colour of the labels in layer 3 and then draw to layer 4, the labels in layer 3 are painted over the graphics painted in level 4. I have tried to set ignoreRepaint() on various components as well as playing around with the opacity and code structure but all to no avail.
Does anyone know how to prevent this from happening?
I won't attach the source code because the project is quite large but I've attached an example that runs as a stand alone program and demonstrates my problem when you hit the "add arrow" button.
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class GraphicsTest {
#SuppressWarnings("serial")
class Painter extends JComponent {
public Painter(int x, int y) {
setBounds(0, 0, x, y);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
private static final int CELL_SIZE = 40;
private static final int NOTE_SIZE = 20;
private JFrame frame;
private static JButton test;
private static JButton clear;
private static JLayeredPane pane = new JLayeredPane();
private static JPanel back = new JPanel();
private static JPanel[][] cellPanels = new JPanel[10][10];
private static JLabel[][] cells = new JLabel[10][10];
private static JPanel[][] notePanels = new JPanel[10][10];
private static JLabel[][][] notes = new JLabel[10][10][4];
private static Painter painter;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GraphicsTest window = new GraphicsTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GraphicsTest() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setSize(600, 700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
pane.setBounds(50, 50, 500, 500);
pane.setLayout(null);
frame.getContentPane().add(pane);
back.setBounds(0, 0, 500, 500);
back.setBackground(Color.BLACK);
pane.add(back, new Integer(100));
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 10; k++) {
String text = "";
if ((i % 2) == 1 && (k % 2) == 1) text = (i + k) + "";
cellPanels[i][k] = new JPanel();
cellPanels[i][k].setBounds(k * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
cellPanels[i][k].setBackground(Color.WHITE);
cellPanels[i][k].setBorder(new LineBorder(Color.BLACK, 1));
cells[i][k] = new JLabel(text);
cells[i][k].setBounds(0, 0, CELL_SIZE, CELL_SIZE);
cells[i][k].setOpaque(false);
cellPanels[i][k].add(cells[i][k]);
pane.add(cellPanels[i][k], new Integer(200));
}
}
boolean display;
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 10; k++) {
if ((i % 2) == 0 && (k % 2) == 0) {
display = true;
} else {
display = false;
}
notePanels[i][k] = new JPanel();
notePanels[i][k].setBounds(k * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE);
notePanels[i][k].setBackground(Color.WHITE);
notePanels[i][k].setBorder(new LineBorder(Color.BLACK, 1));
notePanels[i][k].setLayout(null);
for (int m = 0; m < 2; m++) {
for (int p = 0; p < 2; p++) {
notes[i][k][(m * 2) + p] = new JLabel(30 + "");
notes[i][k][(m * 2) + p].setBounds(m * NOTE_SIZE, p * NOTE_SIZE, NOTE_SIZE, NOTE_SIZE);
notes[i][k][(m * 2) + p].setOpaque(true);
notePanels[i][k].add(notes[i][k][(m * 2) + p]);
}
}
if (display) {
notePanels[i][k].setVisible(true);
} else {
notePanels[i][k].setVisible(false);
}
pane.add(notePanels[i][k], new Integer(300));
}
}
painter = new Painter(500, 500);
pane.add(painter, new Integer(400));
test = new JButton("Add Arrow");
test.setBounds(50, 600, 100, 25);
test.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
highlightNotes();
Arrow.drawArrow(painter.getGraphics(), 20, 20, 400, 400, 20, 30, 40, Color.BLACK, Color.GREEN);
}
});
frame.getContentPane().add(test);
clear = new JButton("Clear");
clear.setBounds(175, 600, 100, 25);
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
painter.repaint();
}
});
frame.getContentPane().add(clear);
}
private static void highlightNotes() {
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 10; k++) {
for (int n = 0; n < 4; n++) {
notes[i][k][n].setBackground(Color.BLUE);
}
}
}
}
static class Arrow {
public static void drawArrow(Graphics g, int tailx, int taily, int headx, int heady,
int shaftw, int headw, int headh, Color outline, Color fill) {
if ((shaftw % 2) == 0) {
shaftw--;
}
if ((headw % 2) == 0) {
headw--;
}
if ((headh % 2) == 0) {
headh--;
}
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
double length = Math.sqrt((double) (((headx - tailx) * (headx - tailx))
+ ((heady - taily) * (heady - taily))));
int tailLength = (int) (length - headw) + 1;
double theta = Math.atan2(heady - taily, headx - tailx);
Point point1 = new Point(0, -(shaftw / 2));
point1 = getTransPoint(point1, theta);
point1.x += tailx;
point1.y += taily;
Point point2 = new Point(tailLength, -(shaftw / 2));
point2 = getTransPoint(point2, theta);
point2.x += tailx;
point2.y += taily;
Point point3 = new Point(tailLength, -(headw / 2));
point3 = getTransPoint(point3, theta);
point3.x += tailx;
point3.y += taily;
Point point4 = new Point((int) length, 0);
point4 = getTransPoint(point4, theta);
point4.x += tailx;
point4.y += taily;
Point point5 = new Point(tailLength, (headw / 2));
point5 = getTransPoint(point5, theta);
point5.x += tailx;
point5.y += taily;
Point point6 = new Point(tailLength, (shaftw / 2));
point6 = getTransPoint(point6, theta);
point6.x += tailx;
point6.y += taily;
Point point7 = new Point(0, (shaftw / 2));
point7 = getTransPoint(point7, theta);
point7.x += tailx;
point7.y += taily;
//Create arrow at tail coordinates passed in
Polygon arrow = new Polygon();
arrow.addPoint(point1.x, point1.y);
arrow.addPoint(point2.x, point2.y);
arrow.addPoint(point3.x, point3.y);
arrow.addPoint(point4.x, point4.y);
arrow.addPoint(point5.x, point5.y);
arrow.addPoint(point6.x, point6.y);
arrow.addPoint(point7.x, point7.y);
//Draw and fill the arrow
g2.setColor(fill);
g2.fillPolygon(arrow);
g2.setColor(outline);
g2.drawPolygon(arrow);
}
private static Point getTransPoint(Point point, double theta) {
int x = (int) ((point.x * Math.cos(theta)) - (point.y * Math.sin(theta)));
int y = (int) ((point.y * Math.cos(theta)) + (point.x * Math.sin(theta)));
return new Point(x, y);
}
}
}

Grid Color Change

can somebody please help me create a chess like board. I need to change the color the grid to black and white. I tried to use a an if statement if (r % 2 = 0) then rectfilcolor, but it colors the hall row.
package grid;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class grid extends JPanel {
public static int High=640;
public static int width=617;
public static int row=3,column=3;
public static JFrame Frame;
public static void main(String[] args) {
grid gride= new grid();
Frame= new JFrame();
Frame.setSize(width, High);
Frame.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
Frame.setVisible(true);
Frame.add(gride);
gride.setBackground(Color.cyan);
}
public void paintComponent(Graphics g) {
for (int r=0; r<4; r++) {
g.drawLine(r*(600/3), 0, r*(600/3), 600);
for (int c=0; c<4; c++) {
g.drawLine(0,(c*(600/3)), 600, (c*(600/3)));
}
}
}
}
-------------------------------------Edited----------------------------------
public void paintComponent(Graphics g){
for (int r=0;r<4;r++){
g.drawLine(r*(600/3), 0, r*(600/3), 600);
if (r%2!=0){
g.setColor(Color.white);
g.fillRect(r*(600/3), 0, r*(600/3), 600);
}
for (int c=0;c<4;c++){
g.drawLine(0,(c*(600/3)), 600, (c*(600/3)));
if(c%2!=0){
g.setColor(Color.black);
g.fillRect(0,(c*(600/3)), 600, (c*(600/3)));
}
}
}
}
}
Always remember to call super.paintComponent(g) to initialize the JPanel canvas correctly.
You can use g.fillRect(x, y, width, height) method to draw each chess cell. Use g.setColor(color) to change the color of the painting.
Therefore:
public void paintComponent(Graphics g) {
super.paintComponent(g);
Color[] colors = {Color.BLACK, Color.WHITE};
int lengthUnit = (600 / 3);
for (int row = 0; row < 3; ++ row) {
for (int col = 0; col < 3; ++col) {
g.setColor(colors[(row + col) % 2]); // alternate between black and white
g.fillRect(row * lengthUnit, col * lengthUnit, lengthUnit, lengthUnit);
}
}
}
Edit: you are almost there, just need to remove some redundant statements in the nested for loop...
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
if ((c + r) % 2 != 0) {
g.setColor(Color.black);
} else {
g.setColor(Color.white);
}
g.fillRect(r * (600 / 3), (c * (600 / 3)), 200, 200);
}
}

Java Swing: Issue painting a grid

The program is supposed to run a cellular automata simulation (think Conway's game of life) on a painted grid and has a start/pause button to, well, start/pause the simulation, which runs on a 1 second interval. As far as I can tell, everything else except for painting the grid (processing, rest of the GUI), works fine.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ConcurrentModificationException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CA_DriverV2 extends JFrame{
private static final Color white = Color.WHITE, black = Color.BLACK;
private Board board;
private JButton start_pause;
public CA_DriverV2(){
board = new Board();
board.setBackground(white);
start_pause = new JButton("Start");
start_pause.addActionListener(board);
this.add(board, BorderLayout.NORTH);
this.add(start_pause, BorderLayout.SOUTH);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setVisible(true);
}
public static void main(String args[]){
new CA_DriverV2();
}
private class Board extends JPanel implements ActionListener{
private final Dimension DEFAULT_SIZE = new Dimension(5, 5);
private final int DEFAULT_CELL = 10, DEFAULT_INTERVAL = 1000, DEFAULT_RATIO = 60;
private Dimension board_size;
private int cell_size, interval, fill_ratio;
private boolean run;
private Timer timer;
private Color[][] grid;
public Board(){
board_size = DEFAULT_SIZE;
cell_size = DEFAULT_CELL;
interval = DEFAULT_INTERVAL;
fill_ratio = DEFAULT_RATIO;
run = false;
//Initialize grid with random values
//NOTE: Add JOptionPane for option to define fill rate and board size?
//ALT: Have a resize(int h, int w) method to resize grid when needed.
//ALT: Have refill(int r) method to restart with different fill ratio.
grid = new Color[board_size.height][board_size.width];
for (int h = 0; h < board_size.height; h++)
for (int w = 0; w < board_size.width; w++){
int r = (int)(Math.random() * 100);
if (r >= fill_ratio)
grid[h][w] = black;
else grid[h][w] = white;
}
timer = new Timer(interval, this);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(board_size.height, board_size.width);
}
#Override
public void paintComponent(Graphics g){
for (int h = 0; h < board_size.height; h++)
for (int w = 0; w < board_size.width; w++){
try{
if (grid[h][w] == black)
g.setColor(black);
else g.setColor(white);
g.fillRect(h * cell_size, w * cell_size, cell_size, cell_size);
} catch (ConcurrentModificationException cme){}
}
}
public void actionPerformed(ActionEvent e) {
//Timer tick processing
if (e.getSource().equals(timer)){
repaint();
Color[][] newGrid = new Color[board_size.height][board_size.width];
for (int h = 1; h < board_size.height; h++)
for (int w = 1; w < board_size.height; w++) {
int surrounding = 0;
//Count black neighbors
for (int i = -1; i <= 1; i++)
for (int j = -1; j <= 1; j++){
if(i != 0 && j != 0){
try{
if(grid[h + i][w + j] == black)
surrounding++;
} catch(ArrayIndexOutOfBoundsException ae){}
}
}
//Generate next iteration
if (surrounding > 5 || surrounding < 2)
newGrid[h][w] = black;
else newGrid[h][w] = white;
}
for (int h = 1; h < board_size.height; h++){
for (int w = 1; w < board_size.height; w++){
grid[h][w] = newGrid[h][w];
System.out.print(grid[h][w] + " ");
}
System.out.println();
}
System.out.println();
}
//Start-Pause button processing
else if(e.getSource().equals(start_pause)){
if(run){
timer.stop();
start_pause.setText("Pause");
}
else {
timer.restart();
start_pause.setText("Start");
}
run = !run;
}
}
}
}
It prints something at the very top, which looks like a sliver of the initial grid overlayed by a sliver of the button, and the rest is the default grey.
Your board Board variable is added BorderLayout.NORTH not BorderLayout.CENTER, so it only fills the top 5 pixels.
And as per my comment, you should never have code like this in your program:
catch(ArrayIndexOutOfBoundsException ae){}
Not only should you not ignore exceptions, but you shouldn't even catch this type of exceptions. Instead create your for loops with a little care so that they can handle the edges.
Also, don't forget to call the super.paintComponent(g) method in your class's override.

Image not showing on JLabel

I've been tasked to make a java replica of Candy Crush Saga.
Right now im quite stuck on the GUI part.
I've decided that each candy will be represented by a JLabel holding the candy icon, and a mouselistener to control the functionality.
What happens is, after i finish running the screen shows, the mouse listeners respond but the image doesn't show, meaning i can press the labels get a response but cannot see the icons. I take this as the labels are on the panel but somehow not visible or the icon is not loaded correctly - although when checking the ImageIcon.toString it shows the path to the file.
Any ideas?
Here is the code:
public class Board extends JPanel {
Candy[][] board;
static final int TILE_SIZE = 55;
static final int TILES_MARGIN = 8;
public Board() {
setFocusable(true);
board = new Candy[13][13];
Candy c;
for (int i = 0; i < 13; i++)
for (int j = 0; j < 13; j++) {
if (i != 0 && i != 1 && j != 0 && j != 1 && i != 11 && i != 12 && j != 11 && j != 12) {
Random rand = new Random();
int randomNum = rand.nextInt((6 - 1) + 1) + 1;
c = new Basic(randomNum, this);
} else {
c = new Basic(0, this);
}
setAt(i, j, c);
}
repaint();
}
public void drawCandy(Graphics g2, Candy candy, int x, int y) {
Graphics2D g = ((Graphics2D) g2);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
int value = candy.getClr();
int xOffset = offsetCoors(x);
int yOffset = offsetCoors(y);
ImageIcon myImg = candy.switchIcon();
JLabel toAdd = new JLabel(myImg);
toAdd.setIcon(myImg);
toAdd.setLocation(xOffset,yOffset);
toAdd.setSize(TILE_SIZE,TILE_SIZE);
toAdd.addMouseListener(new ButtonPressed(x,y,candy));
toAdd.setVisible(true);
if (value != 0)
add(toAdd);
}
private static int offsetCoors(int arg) {
return (arg-2) * (TILES_MARGIN + TILE_SIZE) + TILES_MARGIN;
}
public void paint(Graphics g) {
super.paint(g);
removeAll();
requestFocusInWindow();
g.setColor(Color.black);
g.fillRect(0, 0, this.getSize().width, this.getSize().height);
for (int x = 2; x < 11; x++) {
for (int y = 2; y < 11; y++) {
drawCandy(g, board[x][y], x, y);
}
}
validate();
}
and the JFrame :
public Game() {
super("Candy Crush Game");
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
setSize(600, 600);
setResizable(false);
setLocationRelativeTo(null);
this.board = new Board();
this.score = 0;
this.moves = 20;
this.getContentPane().add(board, BorderLayout.CENTER);
setVisible(true);
board.checkSquare(2, 2, 10, 10);
}
I'm quite frustrated, any help will be great!
Instead of overriding paint() method use paintComponent() method for JPanel.
#Overrie
public void paintComponent(Graphics g) {
super.paintComponent(g);
//your custom painting here
}
Read more
Painting in AWT and Swing
paintComponent() vs paint() and JPanel vs Canvas in a paintbrush-type GUI
There might be some issue in reading image icon. My another post might help you.
ImageIcon does not work with me
Instead of creating new JLabel simply change it's icon.

Categories