package harjutamine;
public class algandmed{
Button[] whitebutton= new Button[2];
Button[] blackbutton= new Button[2];
public algandmed(){
whitebutton[0] = new Button(5, 1);
whitebutton[1] = new Button(5, 3);
blackbutton[0] = new Button(0, 0);
blackbutton[1] = new Button(0, 2);
}
}
This is basic information for my main file.
I have tried algandmed(); and algandmed a = new algandmed(); to call the code in my main file which don't work and I don't know why, I'd be thankful if someone explained why those wouldn't work and what would work.
Main
package harjutamine;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Checkerboard extends JPanel implements ActionListener {
public void drawFrame(Graphics g, int frameNumber, int width, int height) {
int row; // Row number, from 0 to 7
int col; // Column number, from 0 to 7
int x, y; // Top-left corner of square
for (row = 0; row < 8; row++) {
//Kabelaud
for (col = 0; col < 8; col++) {
x = col * 50;
y = row * 50;
if ((row % 2) == (col % 2)) {
g.setColor(Color.BLACK);
} else {
g.setColor(Color.WHITE);
}
g.fillRect(x, y, 50, 50);
}
}
//This is where I try to call the function, but it doesn't work
algandmed aa = new algandmed();
for (Button n: (whitebutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.RED);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
for (Button n: (blackbutton)) {
x = n.col * 50 + 4;
y = n.row * 50 + 4;
g.setColor(Color.BLUE);
g.drawOval(x, y, 40, 40);
g.fillOval(x, y, 40, 40);
}
}
//------ Implementation details: DO NOT EXPECT TO UNDERSTAND THIS ------
public static void main(String[] args) {
JFrame window = new JFrame("Checkerboard");
Checkerboard drawingArea = new Checkerboard();
drawingArea.setBackground(Color.WHITE);
window.setContentPane(drawingArea);
drawingArea.setPreferredSize(new Dimension(390, 390));
window.pack();
window.setLocation(100, 50);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false); // The user can't change the size.
Timer frameTimer = new Timer(20, drawingArea);
window.setVisible(true);
//frameTimer.start(); // commented out so we don't get an animation
} // end main
private int frameNum;
public void actionPerformed(ActionEvent evt) {
frameNum++;
repaint();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawFrame(g, frameNum, getWidth(), getHeight());
}
}
Button
package harjutamine;
public class Button{
int row;
int col;
public Button(int r, int c){
row = r;
col = c;
}
}
I guess what you are trying to say is that your code does not compile. There is no declaration for a Variable whitebutton in your drawFrame method. Therefor the compiler won't compile your code. If you simply paste the code algandmed then you have a declaration of whitebutton. However this is probably not what you wanted. Think about which class should hold/own the Button Arrays. If you decide to put them in the alganmed class you need to provide a correct variable declaration.aa.whitebutton should work because you created an instance of alganmed named aa. Since you are in the same package and whitebutton is default visibility you can access it directly from your main method. Note however that this is not good practice. You should not access another classes internal data directly. Try to think of methods that encapsulate the data of alganmed instead.
Related
I am trying two draw a 2D array(dynamic) of random boxes with different colors,
this is the code:
Main.java
public class Main {
public static void main(String[] args) {
CustomPanel f = new CustomPanel (4, 5);
JFrame frame = new JFrame("Testing");
frame.add(f);
frame.setSize(1000, 1000);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
CustomPanel.java:
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class CustomPanel extends JPanel {
Drawable [][]boxes;
public CustomPanel (int rows, int cols)
{
this.setLayout(null);
boxes = new Drawable[rows][cols];
Random rand = new Random();
for(int i = 0 ; i < rows ; i ++)
{
for(int j = 0 ; j < cols ; j++)
{
switch(rand.nextInt(3))
{
case 0:
boxes [i][j] = new Box1();
break;
case 1:
boxes [i][j] = new Box2();
break;
case 2:
boxes [i][j] = new Box3();
break;
}
}
}
}
public void paintComponent (Graphics g) {
super.paintComponent(g);
Rectangle t = g.getClipBounds();
int box_width = t.width/ this.boxes[0].length;
int box_heigt = t.height/ this.boxes.length;
for(int i = 0 ; i < this.boxes.length; i ++)
{
for(int j = 0 ; j < this.boxes[0].length; j++)
{
System.out.println("" + i + ":" + j);
boxes [i][j].draw(i * box_width, j * box_heigt, box_width, box_heigt, g);
}
}
}
}
Drawable.java:
import java.awt.Graphics;
public interface Drawable {
public abstract void draw(int x, int y, int width, int height, Graphics g);
}
Box1(Box2, Box3 are the same, just different colors):
import java.awt.Color;
import java.awt.Graphics;
public class Box1 implements Drawable{
public Box1 () { //default constructor
}
#Override
public void draw(int x, int y, int width, int height, Graphics g) {
g.setColor(Color.CYAN);
g.fillRect(x, y, width, height);
}
}
The problem is that some of the boxes do not appear at the panel at all(altought I do iterate over both rows and columns).
I debugged it but could not find out why it happens(it might be silly - i know)
Box1(Box2, Box3 are the same, just different colors):
Don't create separate classes, just pass the Color as a parameter.
do you mean at paintComponent ? how? I guess this.getParent().getSize().width ?
Yes, paintComponent().
No, you don't get the parent. You are doing custom painting on a JPanel. You want the width/height of the panel using the methods I suggested in my comment.
The problem is that some of the boxes do not appear at the panel at all
You have your x/y values reversed when you paint each Box. The "i" variable represents the rows (or the y value) and the "j" variable represents the columns (or the x value).
So your logic should b:
for(int i = 0 ; i < this.boxes.length; i ++)
{
for(int j = 0 ; j < this.boxes[0].length; j++)
{
//boxes [i][j].draw(i * box_width, j * box_heigt, box_width, box_heigt, g);
boxes [i][j].draw(j * box_width, i * box_heigt, box_width, box_heigt, g);
}
}
instead of using the Array length property to control the rows/columns, why not just save the row/column parameters as variable in your class which might help make your code easier to read.
I am attempting to draw the US flag using java. I have pretty much done all this coding using lots of variables. It should be at least displaying the stripes, blue box, and the stars(ovals in this case). However, when I run the code through the compiler, and run it, all it displayes is a white background with a red stripe on the top. Could I please receive some help to see where my error is? I have tried everything.
Here is the code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
public class UsFlag extends JPanel {
int w = getWidth();
int h = getHeight();
int numberStripes = 13;
int numStarCol = 8;
int numStarRow = 6;
int stripeHeight = h/numberStripes;
int boxWidth = (int)(w*0.4);
int boxHeight = 7 * stripeHeight;
int starWidth = boxWidth/numStarCol;
int starHeight = boxHeight/numStarRow;
/*public UsFlag() {
//ask user to enter number of stripes, star columns, and star rows
}*/
#Override
public void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
//Background
g.setColor(Color.RED);
g.fillRect(0, 0, w, h);
//Stripes
g.setColor(Color.WHITE);
for (int i = 0; i < numberStripes; i += 1) {
g.fillRect(0,stripeHeight, w, stripeHeight);
stripeHeight = stripeHeight + 45;
}
//Blue Rect
g.setColor(Color.BLUE);
g.fillRect(0, 0, boxWidth, boxHeight);
//stars
int y = 0;
int x = 0;
for (int j = 0; j < numStarRow; j++){
for (int i = 0; i < numStarCol; i++){
g.setColor(Color.WHITE);
g.fillOval(5, 5, starWidth, starHeight);
x += starWidth;
}
y += starHeight;
x = 0;
}
}
public static void main(String[] args) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(400, 400);
window.setContentPane(new UsFlag());
window.setVisible(true);
}
}
The first two parameters for the fillRect() method and the fillOval() method are considered coordinates (x & y) for the object you want to paint. This means that for x you need to place a integer pixel value as to where you want the Left edge of the object is to Start being painting from along the horizontal plain, and for y you need to place a integer pixel value as to where you want the Top edge of the object is to Start being painting from along the vertical plain. For fillRect() for example:
g.fillRect(20, 20, 100, 30);
The other two parameters are for the Width (w) and Height (h) in pixels of the object to paint. Use the the variable i from your for loop (y = i + 30; for example) to draw objects below one another. Read this for more information.
I have the following Processing program:
//using Papplet instead of STDraw to visually represent my grid, created by Mahmed Ibrahim
import java.awt.Color;
import processing.core.*;
import processing.core.PApplet;
public class C4Grid extends PApplet {
PShape s;
PShape[][] circleSpaces;
boolean[][] circleSpacesFilled;
boolean[][] circleHasYelowPiece;
boolean[][] circleHasRedPiece;
final float SPACES_BETWEEN_ROWS = 110;
final float SPACES_BETWEEN_COLUMNS = 130;
public C4Grid(){}
public void setup() {
System.out.println("it got to here where it breaks");
size(1000, 1000, P2D);
// Making the shape of the grid using vertices
// so I'm manually drawing my polygon.
s = createShape();
s.beginShape();
s.fill(34, 56, 100);
s.tint(34, 56, 100);
s.stroke(0);
s.strokeWeight(5);
s.vertex(400, 400);
s.vertex(400, -440);
s.vertex(360, -440);
s.vertex(360, -400);
s.vertex(-360, -400);
s.vertex(-360, -440);
s.vertex(-400, -440);
s.vertex(-400, 420);
s.vertex(-420, 420);
s.vertex(-420, 440);
s.vertex(-360, 440);
s.vertex(-360, 420);
s.vertex(-380, 420);
s.vertex(-380, 400);
s.vertex(380, 400);
s.vertex(380, 420);
s.vertex(360, 420);
s.vertex(360, 440);
s.vertex(420, 440);
s.vertex(420, 420);
s.vertex(400, 420);
s.vertex(400, 420);
s.vertex(400, -440);
s.vertex(400, 400);
s.endShape();
System.out.println("it got to here where it breaks");
// using a 2D array to create a grid of circles
// which will represent the spaces on the grid
circleHasYelowPiece = new boolean[7][6];
circleHasRedPiece = new boolean[7][6];
circleSpacesFilled = new boolean[7][6];
circleSpaces = new PShape[7][6];
for (int row = 0; row < 7; row++) {
for (int column = 0; column < 6; column++) {
circleSpaces[row][column] = createShape(ELLIPSE, -380 + (row) * SPACES_BETWEEN_ROWS,
-370 + (column) * SPACES_BETWEEN_COLUMNS, 100, 100);
circleSpaces[row][column].disableStyle();
stroke(0);
strokeWeight(5);
circleSpacesFilled[row][column] = false;
circleHasRedPiece[row][column] = false;
circleHasYelowPiece[row][column] = false;
}
}
}
public void draw() {
translate(width / 2, height / 2);
shape(s);
for (int row = 0; row < 7; row++) {
for (int column = 0; column < 6; column++) {
shape(circleSpaces[row][column]);
}
}
}
public boolean piecePlaced(int column, Color pieceColor) {
column = column - 1; // the choice are form 1-7 but in an array its 0-6;
boolean moveDone = false;
int i = 5;
Color red = new Color(255, 0, 0);
while (i >= 0) {
if (circleSpacesFilled[column][i] == false) {
circleSpacesFilled[column][i] = true;
if (pieceColor.equals(red)) {
circleHasRedPiece[column][i] = true;
circleSpaces[column][i].fill(255, 0, 0);
circleSpaces[column][i].tint(255, 0, 0);
} else {
circleHasYelowPiece[column][i] = true;
circleSpaces[column][i].fill(255, 255, 0);
circleSpaces[column][i].tint(255, 255, 0);
}
return true;
}
}
return false;
}
}
When I run it, I get this NullPointerException. Notice that the exception is coming from within Processing's libraries - it's not directly caused by my own code!
The 3 lines that are suspect are:
currentGame = new C4Game(player1Is,player2Is,player1Color,player2Color);
theGrid = new C4Grid(); theGrid.setup();
s= createShape(); near the top of setup()
currentGame, theGrid, and s are all non-null (I've checked countless times).
Even when I test each line in isolation, I get an error in anything that related to the PShape class. I got rid of every PShape object and it worked, but is there a way to fix it so I can use PShape as part of my code?
When I run your code, I don't get a NullPointerException. I get an error that says this:
When not using the PDE, size() can only be used inside settings().
Remove the size() method from setup(), and add the following:
public void settings() {
size(1000, 1000, "processing.opengl.PGraphics2D");
}
And the error says it all. When you're using Processing as a library, you can't call the size() function from the setup() function. Call it from the settings() function instead.
If I make that change, your code runs fine:
I have been looking at this one for a while and it doesn't make sense. When I start my program, I set the background color of a grid of rectangles to a specific color using the SetupLawn call from my main function in a different file. That part works fine. Then when I try to change the color later by calling the SetupLawn function again with a new color it doesn't change. I put prints in the SetupLawn function and the color I am passing is getting there correctly but as soon as paintComponent gets called the value of currentColor is back to being what it was originally. I verified this with a debug print as well.
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class Lawn
{
public static class SetupLawn extends JPanel
{
private List<Point> lawn;
Color currentColor;
public SetupLawn(Color color)
{
lawn = new ArrayList<>(25);
currentColor = color;
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
for (Point cell : lawn)
{
int cellX = cell.x;
int cellY = cell.y;
g.setColor(currentColor);
g.fillRect(cellX, cellY, 50, 50);
}
//Set grid color and draw border
g.setColor(Color.BLACK);
g.drawRect(10, 10, 800, 500);
for (int i = 10; i <= 800; i += 50)
{
g.drawLine(i, 10, i, 510);
}
for (int i = 10; i <= 500; i += 50)
{
g.drawLine(10, i, 810, i);
}
for (int i = 60; i <= 750; i += 50)
{
for (int j =60; j <= 450; j += 50)
{
lawn.add(new Point(i, j));
}
}
}
}
}
Here is the way I was calling it.
Lawn.SetupLawn lawn = new Lawn.SetupLawn(spring);
I can see now why this method was not a good idea. It was really late at night when I was working on this and Java is not a strong language for me.
I wrote a checkerboard program (shown below). My problem is that I can't figure out how to center it with resize, and have it resize proportionately.
I added in a short statement. Int resize (shown below) I did something similiar with a previous program regarding a bullseye where I used a radius. I just haven't the slightest clue how to implement that in here.
import java.awt.*;
import javax.swing.JComponent;
public class CheckerboardComponent extends JComponent {
#Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.RED);
int s = 12;
int x = s;
int y = s;
// int resize = Math.min(this.getHeight(), this.getWidth()) / 8 ;
for (int i = 0; i < 8; i++) {
// one row
for (int j = 0; j < 8; j++) {
g2.fill(new Rectangle(x, y, 4 * s, 4 * s) );
x += 4 * s;
if(g2.getColor().equals(Color.RED)){
g2.setColor(Color.BLACK);
}else{
g2.setColor(Color.RED);
}
}
x = s;
y += 4 * s;
if(g2.getColor().equals(Color.RED)){
g2.setColor(Color.BLACK);
}else{
g2.setColor(Color.RED);
}
}
}
}
here is a viewer program
import javax.swing.*;
public class CheckersViewer {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(430, 450);
frame.setTitle("Checkerboard");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CheckerboardComponent component = new CheckerboardComponent();
frame.add(component);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Hmm... Here's one idea then, though it probably isn't a good one (I'm also not that good with jComponent and jFrame, so there's probably a better way and a more suited person)
I believe the component object has a built-in method called getSize(). If you can relate the size of the rectangle to the size of the window, then it could be resizable. Obviously there would be more code and arguments, but for example:
public void drawStuff(Component c)
{
...
Dimension size = c.getSize();
double RectWidth = (size.width)*(.05);
...
}
check this out for more complete examples:
http://www.javadocexamples.com/java/awt/Component/getSize().html
And I apologize I can't be of more help.