Double Static Array Throws Exception - java

I am working on an game assignment for my class in eclipse. I have been getting an error:
ClassNotFoundException(throwable);
It stops in
public static Jewel[][] grid = new Jewel[8][8];
While running the debugger it doesnt seem to enter the new Jewel[8][8]
i certanly have the Jewel Class in the same package, and i cant figure out why it cant find the class. I am assuming that it is trying to generate a different class or the static portion of the class is not being generated at compile time. Any additional comments are welcome;
here is the whole class this is located in
package game;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class PlayArea extends JPanel {
private static final long serialVersionUID = -9165676032115582474L;
public static Jewel[][] grid = new Jewel[8][8];
public PlayArea(){
this.setPreferredSize(new Dimension(Common.jewelWidth*Common.rowColLength,Common.jewelWidth*Common.rowColLength));
this.setLayout(null);
for(int i = 0; i < Common.rowColLength; i++){
for (int j = 0; j < Common.rowColLength; j++){
grid[i][j] = new Jewel();
}
}
}
#Override
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i <Common.rowColLength;i++){
for(int j = 0; j < Common.rowColLength; j++){
grid[i][j].drawJewel(i, j, g2);
}
}
Jewel grid2 = new Jewel();
grid2.drawJewel(1, 1, g2);
}
}

public static Jewel[][] grid = new Jewel[8][8];
This will not create instances of Jewel class but merely references to it. You have to explicitly iterate over your 2D array and create new Jewel instances.
grid[i][j] = new Jewel();
This is where it will go inside the constructor if you have some code in your default constructor.

While running the debugger it doesnt seem to enter the new Jewel[8][8].
It wont't enter jewel[8][8] because array indices start from 0. i.e; from 0-7 (count=8)

Related

Random circles applet java

I am new to programming and trying to write a graphics program in java that displays ovals of different sizes and colors, however, I am not able to get the program to display the ovals in applet window. Does anyone have any suggestions/input on where I went wrong here? Please see an example of my paint method below:
public void paint(Graphics g)
{
for(int i=0; i<n; i++)
{
x[i] = (int)(600* Math.random() +1);
y[i] = (int)(600* Math.random() +1);
}
int c= (int)(255*Math.random()); //random foreground color
int a= (int)(255*Math.random());
int t= (int)(255*Math.random());
Color f = new Color(c,a,t);//variables have been declared in init
g.setColor(f);
g.fillOval(rand(0, 600), rand(0, 600), r = rand(5, 100), r);
sleep(100);
cnt += 1;
if(cnt >= 500) clearScreen();
else update(g);
}
I modified a recent school project (we were supposed to make a hot air balloon) so excuse the naming of some of the stuff:
import java.awt.*;
import javax.swing.*;
public class Balloon extends JComponent {
public static void main(String args[]){
JFrame frame = new JFrame("balloons");
frame.setSize(200,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
Balloon balloon = new Balloon();
frame.setContentPane(balloon);
}
public void paint(Graphics g){
super.paint(g);
for(int i = 0; i<20; i++){
int c= (int)(255*random()); //random foreground color
int a= (int)(255*random());
int t= (int)(255*random());
g.setColor(new Color(c,a,t));
g.fillOval((int)(200*random()),(int)(200*random()),(int)(30*random()),(int)(30*random()));
}
}
public double random(){
return Math.random();
}
}
Its rather small at the moment so you may want to change around some of the variables... however it does what you asked.
In terms of where you went wrong... it appears you have a loop that put values into two arrays... however I don't see a second array that goes through and draws all the ovals... In my code, I generate all the coordinates, colours, and print it out all at once.

(Java) Drawn Rectangles do not appear

So am working on a School Project, and I want to draw a game board made out of Rectangles which are saved in an array. I managed to do that, but only the last drawn Rectangle Stays on the Panel. I'm really desperate and i don't know where my mistake is.
The Field is a 4x5 field. The Coordinates saved in the Tile Class:
the first two represent the upper left Corner
the last two represent the bottom right corner of it
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class quoVadis{
public static void main(String[] args) {
new Frame();
}
}
class Tile {
Random rGen = new Random();
int sX,sY,eX,eY;
Color farbe;
public Tile(int sX, int sY,int eX,int eY){
this.sX = sX;
this.sY = sY;
this.eX = eX;
this.eY = eY;
farbe = new Color(rGen.nextInt(156)+100,rGen.nextInt(156)+100,rGen.nextInt(156)+100);
}
}
class Frame extends JFrame{
private Game game;
final int GAMESIZE = 400;
final int PANELSIZE = GAMESIZE/5;
public Frame() {
super("Quo Vadis");
this.setSize(GAMESIZE, GAMESIZE*5/4);
this.setLocation(50, 50);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game = new Game(GAMESIZE, PANELSIZE);
game.setLayout(null);
game.setBackground(Color.WHITE);
this.getContentPane().add(game);
this.setVisible(true);
}
}
class Game extends JPanel{
int GAMESIZE;
int PANELSIZE;
private Tile field[][]=new Tile[4][5];
Random rGen = new Random(4711);
Tile stein;
public Game(int g, int p) {
GAMESIZE = g;
PANELSIZE = p;
// The Mistake has to be in this following Part:
int idx=0;
for(Tile i:levels){
for(int j = i.sX; j <= i.eX; j++){
for(int k = i.sY; k <= i.eY; k++){
field[j][k] = levels[idx];
}
}
idx++;
}
for(int k = 0; k <= 4; k++){
for(int j = 0; j <= 3; j++){
if(field[j][k]==null)continue;
stein=field[j][k];
draw((field[j][k].sX * PANELSIZE) , (field[j][k].sY * PANELSIZE) , ((((field[j][k].eX-field[j][k].sX) + 1) * PANELSIZE) -1), ((((field[j][k].eY-field[j][k].sY)+ 1) * PANELSIZE) -1));
}
}
this.setVisible(true);
}
int rx, ry,rdx,rdy;
private void draw(int a, int b, int c, int d){
rx=a;
ry=b;
rdx=c;
rdy=d;
repaint(rx,ry,rdx,rdy);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(stein.farbe);
g.fillRect(rx, ry, rdx, rdy);
}
Tile[] levels = {
new Tile(1,0,2,1),
new Tile(0,0,0,1),
new Tile(3,0,3,1),
new Tile(0,2,0,3),
new Tile(1,2,2,2),
new Tile(3,2,3,3),
new Tile(0,4,0,4),
new Tile(1,3,1,3),
new Tile(2,3,2,3),
new Tile(3,4,3,4),
};
}
I already checked the Position of the Rectangles in numbers and they are correct in every way so they do not overlap or something like that.
Sorry for my bad english, it's not my primary language.
You need to draw each rectangle inside of your paintComponent method every time.
Currently you are calling your draw method for one rectangle then you call repaint and draw that single rectangle. paintComponent will redraw the entire panel each time it is called. This means that it will on preserve the last rectangle (the rest were "repainted over".
You want to loop through all of your tiles and use the drawRect method to draw them inside of your paintComponent method so they will be drawn every time.
public void paintComponent(Graphics g) {
super.paintComponent(g)
for(int k = 0; k <= 4; k++){
for(int j = 0; j <= 3; j++){
if(field[j][k]==null)continue;
stein=field[j][k];
g.setColor(stein.farbe);
g.fillRect((field[j][k].sX * PANELSIZE) , (field[j][k].sY * PANELSIZE) , ((((field[j][k].eX-field[j][k].sX) + 1) * PANELSIZE) -1), ((((field[j][k].eY-field[j][k].sY)+ 1) * PANELSIZE) -1));
}
}
}

for loop gets error "illegal start of type"

so im trying to create a program in java which will create a 10 by 10 matrix, with each element displaying either a 1 or a 0 randomly. Here is what i have so far:
package random.matrix;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
class ex2 extends JFrame {
class Random {
GridLayout setLayout= new GridLayout(10, 10);
for (int i = 0; i < 10; i++) {
int number = (int) (Math.random() * 2);
String str = Integer.toString(number);
add(new JLabel(str, JLabel.CENTER));
}
}
public static void main(String[] args) {
JFrame frame = new ex2();
frame.setTitle("RandomMatrix");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
As far as I can tell, this program should run perfectly. However, every time I try, it says something along the lines of "illegal start of type," referring specifically to the for loop line. Can anyone help me troubleshoot this? I've never encountered an error quite like this one.
You need to place your code in a code block such as a method or constructor rather than the class block of an inner class
/**
* TODO: Refactor later NOT to extend from JFrame
*/
class MyFrame extends JFrame {
void initComponents() {
GridLayout setLayout = new GridLayout(10, 10);
for (int i = 0; i < 10; i++) {
...
}
}
...
}
You can't have arbitrary statements inside a class definition. Perhaps you want to put it in the constructor?
class Random {
public Random() {
GridLayout setLayout = new GridLayout(10, 10);
for (int i = 0; i < 10; i++)
{
int number = (int) (Math.random() * 2);
String str = Integer.toString(number);
setLayout.add(new JLabel(str, JLabel.CENTER));
}
}
}
Or, you could just create another method and place it in there.

Changing colors of GridLayout elements

Note: this question may look a bit like another I've posted a few weeks ago. Back then I was not working with adding the buttons as arrays, thats what makes it more difficult for me this time.
I'm working with a chessgame, and I have been able to set up a board of 64 squares on my own. However it seems to be a little too complicated for me to manage adding the colors to the squares.
My code looks like this:
Chess.java
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Chess implements config {
public static void main(String[] args) {
int[] squareArray;
squareArray = new int[65];
int i = 1;
JFrame frame = new JFrame("Chessboard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(ROWS, COLS, 2, 2));
for (i = 1; i < 65; i++) {
squareArray[i] = i;
frame.add(new JButton("" + squareArray[i]));
}
frame.setSize(800, 800);
frame.setVisible(true);
}
}
Piece.java
import java.awt.Color;
import javax.swing.JFrame;
public class Piece extends JFrame implements config {
public Piece (int n) {
setBackground(calcColor(n));
}
public void Pieces() {
new Pieces();
//This class contains nothing at the moment.
}
Color calcColor(int n) {
boolean everysecondSquare = (n % 2 == 0);
boolean everysecondRow = ((n / ROWS) % 2 == 0);
return (everysecondSquare != everysecondRow ? P1Color : P2Color);
}
}
config.java
import java.awt.Color;
public interface config {
public int ROWS = 8;
public int COLS = 8;
Color P1Color = (new Color(245,222,179));
Color P2Color = (new Color(244,164,96));
}
I'm very aware that this probably is pretty bad coded as I am very new to Java. I would be very happy and thankful if someone could help me out with the colors here as I have been stuck for several days now without getting any further. I don't expect someone to finish the code for me, but merely help me on the way to get there. :)
What about this?
for (i = 1; i < 65; i++) {
squareArray[i] = i;
JButton b=new JButton("" + squareArray[i]);
b.setBackground(desiredColorHere);
frame.add(b);
}

Points not being properly read by MouseListener

I'm having a problem where I can't properly access my instance Point data.
I create an multi-dimensional array of GridPanels, and instantiate each with a Point.
When first created, everything works as expected.
pic1 http://img.skitch.com/20100218-fciwr7t73ci2gajafmfxa2yf9q.jpg
When I click on a GridPanel however, the Listener class always receives the Point from the last GridPanel that was created ( (3, 3) in this case.)
When I pass an int instead of a Point however, the int for the GridPanel that was clicked is shown (like you'd expect).
Anyone know what's going on here?
Thanks
import javax.swing.JFrame;
/**
* Driver class.
*/
public class Test {
/**
* The main method.
* #param args Command line arguments.
*/
public static void main(String[] args) {
JFrame frame = new JFrame("TEST");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TestPanel panel = new TestPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
import java.awt.GridLayout;
import java.awt.Point;
import javax.swing.JPanel;
/**
* Creates a 4 by 4 grid of GridPanels.
*/
public class TestPanel extends JPanel {
static final int ROW_SIZE = 4;
static final int COL_SIZE = 4;
private GridPanel[][] g = new GridPanel[ROW_SIZE][COL_SIZE];
public TestPanel() {
Point coords = new Point();
setLayout(new GridLayout(ROW_SIZE, COL_SIZE));
for (int i = 0; i < ROW_SIZE; i++) {
for (int j = 0; j < COL_SIZE; j++) {
coords.setLocation(i, j);
g[i][j] = new GridPanel(coords);
add(g[i][j]);
}
}
}
}
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* Contains the MouseListener.
*/
public class GridPanel extends JPanel {
private JLabel label;
private Point p;
public GridPanel(Point p) {
this.p = p;
label = new JLabel("" + p);
add(label);
setBackground(Color.WHITE);
setPreferredSize(new Dimension(200, 50));
addMouseListener(new SelectListener());
}
private class SelectListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
label.setText("" + p);
}
}
}
The problem is that you are re-using the same point, stored in coords. You need to create a new point for each grid element. It looks to you as if each panel has a different point value stored in it because each panel has a different label. But in the line
label = new JLabel("" + p);
you are creating a String that contains the current value of p. But p can change later, and the label won't change with it.
So the easiest fix for your problem is to change the line
this.p = p;
to
this.p = new Point(p); // Create a defensive copy.
It looks like you may be currently somewhat confused about the difference between objects and fields. For example,
Point p = new Point(3, 4);
Point p2 = p;
p.x = 7;
System.out.println(p2.x);
will yield 7, as there is only one point being manipulated, though it's pointed to by two fields. Using = doesn't create a copy of the point.
(Apologies if I'm explaining things you already know!)
The point is and object so it is passed by reference. This means all your panels reference the same Point. Since you are changing the location on it all the time - the last will be shown.
You have to create new Point every time in the loop:
public TestPanel() {
setLayout(new GridLayout(ROW_SIZE, COL_SIZE));
for (int i = 0; i < ROW_SIZE; i++) {
for (int j = 0; j < COL_SIZE; j++) {
g[i][j] = new GridPanel(new Point(i, j));
add(g[i][j]);
}
}
}
i change setPreferredSize(new Dimension(w, h)); this is done.
but in my program i need change my frame size every time. so how can fit gridpanel in that case.... if frame size (1200,800) or (1170,920) i am not using JLabel here.
thankyou for answering
in place of this frame.pack(); i use frame.setSize(W,H);
in a gridpanel add
setPreferredSize(new Dimension(x,y));
setBorder(BorderFactory.createLineBorder(Color.red));
i remove JLabel
where x = w / col_size; y = h / row_size;
now when i run Test.java grid are not fitted in my frame;

Categories

Resources