Java: Mac terminal cannot display Java Graphics - java

I am trying to draw checkerboard using Java.
I am new to Java. So any advices would be helpful.
UPDATE: I added in the main method. I compiled it successfully in the Mac terminal. However, when I did java Checkerboard, there was an ICON appearing at the bottom and then it disappeared and no graphics appeared. What's wrong in here? The code is as follow:
import acm.graphics.*;
import acm.program.*;
/*
* This class draws a checkerboard on the graphics window.
* The size of the chcekerboard is specified by the constants NROWS
* and NCOLUMNS, and the checkerboard fills the vertical space available.
*/
public class Checkerboard extends GraphicsProgram {
public static void main(String[] args){
Checkerboard c = new Checkerboard();
c.run();
}
// Number of rows
private static final int NROWS = 8;
//Number of columns
private static final int NCOLUMNS = 8;
//Runs the program
public void run() {
int sqSize = getHeight() / NROWS;
for(int i = 0; i < NROWS; i++) {
for(int j = 0; j < NCOLUMNS ; j++) {
int x = j * sqSize;
int y = i * sqSize;
GRect sq = new GRect(x,y,sqSize,sqSize);
sq.setFilled( ((i+j) % 2) != 0);
add(sq);
}
}
}
}

Your class needs to have a main method with the signature
public static void main(String[] args)
for you to be able to run it.
After your edit:
Maybe you need a loop in the main method calling the run method? Something like:
boolean exit = false;
while (!exit) {
c.run();
// if something set exit to true
}

You seem to be lacking the main method: public static void main(String[] args) that is run when you start your program.
(removed the edit I did before, which was meant to go in my own post)

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.

How to print an object several times in Java?

I am working on a program that should print a pyramid. Base of the pyramid is 14 blocks. Blocks are (30,12) pixels. Dimensions of an applet which pyramid will be printed on is (800,400). Base block starts at (100,380). I figured that if I duplicate that block and move it 30 pixels in x-direction 14 times, I will finish the base. I am having a trouble to do so. I used for loop to duplicate and move the block but doesn`t work.
What am I doing wrong?
import acm.graphics.GRect;
import acm.program.*;
public class Pyramid extends GraphicsProgram
{
public static final int BRICK_WIDTH = 30;
public static final int BRICK_HEIGHT = 12;
public static final int BRICK_IN_BASE = 14;
public void run()
{
setSize(800,400);
GRect rec = new GRect (100,380,BRICK_WIDTH,BRICK_HEIGHT);
for (int i = 0; i<14; i++)
{
rec.move(30,0);
add(rec);
}
}
}
Look at the condition in your for-loop. You're telling the compiler too loop while i is bigger than 14, which is never true.
Change it too i < 14.
There is only one rectangle in your program. The add() method adds the same object multiple times; you will need to create a new one every time.
You need to change your for loop condition, i is never greater than 14, should be less than.
Also you should make a new Grect, and just change the x value for each new one by 30
import acm.graphics.GRect;
import acm.program.*;
public class Pyramid extends GraphicsProgram
{
public static final int BRICK_WIDTH = 30;
public static final int BRICK_HEIGHT = 12;
public static final int BRICK_IN_BASE = 14;
public void run()
{
setSize(800,400);
int x = 100;
int y = 380;
for (int i = 0; i<14; i++)
{
GRect rec = new GRect (x, y,BRICK_WIDTH,BRICK_HEIGHT);
x += BRICK_WIDTH;
add(rec);
}
}
}
You aren't duplicating it, you're simply moving it. Try the following:
public void run() {
setSize(800,400);
int x=100, y=380;
GRect rec;
for (int i = 0; i<BRICK_IN_BASE; i++) {
rec = new GRect (x, y, BRICK_WIDTH, BRICK_HEIGHT);
add(rec);
x += BRICK_WIDTH;
}
}

Intergrating Proclipsing into Eclipse Project, screen won't appear

I have a project that on it's own functions as I would like it to. It's a small game about the player (a blob) picking up randomly spawning items in an attempt to keep their "happiness" from hitting 0.
I originally wrote it in BlueJ, but I asked a friend who is more adept in programming about giving it graphics. He said that while the swing package would work, it would be better in Eclipse with Processing.
I set it up with him on my computer over Skype, moved all my files from BlueJ to Eclipse, and began working on making a class for the visuals to function it.
Here's the code (All variables and functions from the Map class are functioning):
public void setup()
{
//int x = gameMap.getXScale()*5 + 5*(xSC+2);
//int y = gameMap.getYScale()*5 + 5*(ySC+2) + 150;
gameMap = new Map(MapTypes.treasureRoom(), BlobTypes.trBlob());
xSC = gameMap.getXScale();
ySC = gameMap.getYScale();
sze = 100;
spc = 5;
int x = gameMap.getXScale()*5 + 5*(xSC+2);
int y = gameMap.getYScale()*5 + 5*(ySC+2) + 150;
size(x,y);
}
public void draw()
{
int[] rgb = gameMap.getBlob().getRGBVal();
int r = 204;
int g = 102;
int b = 0;
Node[][] n = gameMap.getMapOfNodes();
background(0);
for(int i = 0; i < ySC; i ++){
for(int j = 0; j < xSC; j++){
if(n[j][i].getNodeType() == 0){
r = 128;
g = 128;
b = 128;
}else if(n[j][i].getNodeType() == 1){
r = rgb[0];
g = rgb[1];
b = rgb[2];
}else if(n[j][i].getNodeType() == 2){
r = 204;
g = 153;
b = 255;
}else if(n[j][i].getNodeType() == 3){
r = 0;
g = 0;
b = 0;
}
rectt(j*10+spc, i*10+spc, sze, sze, 5, r, g, b);
}
}
fill(100);
rect(50, 50, 100, 100);
}
void rectt(float x, float y, float w, float h, float ra, int r, int b, int g)
{
fill(r,b,g);
rect(x, y, w, h, ra);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
It is inside a Game() class that extends PApplet. When I try running it (as an application), no screen shows up at all. What do I do?
EDIT: The Node[][] near the beginning of draw() is an array of each individual point on the Map that the player can be. Also, the MapTypes and BlobTypes objects are just a collection of methods for storing different Map objects and Blob (the player) objects.
you aren't calling anything in your main method class
public static void main(String[] args) {
// TODO Auto-generated method stub
}
I can't personally tell you what all you need to call from this class but it should be something like this
public static void main(String[] args) {
ThisClass main = new ThisClass(parameters if any);
main.setup();
while(game is not over){
main.draw();
update other game logic
}
}
As a note, one iteration of your while loop is equvilant to one frame. So everything you want to be accomplished per frame, must be placed in here.

Why wont squares show up after repaint()?

I posted this question a bit earlier and was told to make it SSCCE so here goes (if I can make any improvements feel free to let me know):
I'm wondering why when my button "confirm" is clicked the old squares disappear and the redrawn squares do not appear on my GUI (made with swing). The Squares class draws 200 spaced out squares with an ID (0, 1, 2, or 3 as String) inside obtained from a different class (for the purpose of this question, let's assume it is always 0 and not include that class). For clarification: Squares draws everything perfectly the first time (also retrieves the correct IDs), but I want it to redraw everything once the button is clicked with new IDs.
Code for Squares:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
public class Squares extends JPanel{
private ArrayList<Rectangle> squares = new ArrayList<Rectangle>();
private String stringID = "0";
public void addSquare(int x, int y, int width, int height, int ID) {
Rectangle rect = new Rectangle(x, y, width, height);
squares.add(rect);
stringID = Integer.toString(ID);
if(ID == 0){
stringID = "";
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontMetrics fm = g2.getFontMetrics();
int fontAscent = fm.getAscent();
g2.setClip(new Rectangle(0,0,Integer.MAX_VALUE,Integer.MAX_VALUE));
for (Rectangle rect : squares) {
g2.drawString(stringID, rect.x + 7, rect.y + 2 + fontAscent);
g2.draw(rect);
}
}
}
Code for GUI:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIReserver extends JFrame implements Runnable{
private int myID;
private JButton confirm = new JButton("Check Availability and Confirm Reservation");
private JFrame GUI = new JFrame();
private Squares square;
public GUIReserver(int i) {
this.myID = i;
}
#Override
public void run() {
int rows = 50;
int seatsInRow = 4;
confirm.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
GUI.getContentPane().remove(square);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this does not show up at all (could be that it wasn't drawn, could be that it is out of view etc...)
GUI.repaint(); //the line in question
}
});
GUI.setLayout(new FlowLayout());
GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GUI.setLocation(0,0);
GUI.setExtendedState(JFrame.MAXIMIZED_BOTH);
square = new Squares();
int spaceNum = 0;
int rowNum = 0;
int offsetX = 200;
int offsetY = 0;
for(int i = 0; i < rows * seatsInRow; i++){
square.addSquare(rowNum * 31 + offsetX,spaceNum * 21 + 50 + offsetY,20,20, 0); //normally the 4th parameter here would retrieve the ID from the main class
rowNum++;
if(rowNum == 10){
rowNum = 0;
spaceNum++;
}
if(spaceNum == 2){
spaceNum = 3;
rowNum = 0;
}
if(spaceNum == 5){
spaceNum = 0;
offsetY += 140;
}
}
GUI.getContentPane().add(square); //this shows up the way I wish
GUI.add(confirm);
GUI.pack();
GUI.setVisible(true);
}
}
Code for main:
public class AircraftSeatReservation {
static AircraftSeatReservation me = new AircraftSeatReservation();
private final int rows = 50;
private final int seatsInRow = 4;
private int seatsAvailable = rows * seatsInRow;
private Thread t3;
public static void main(String[] args) {
GUIReserver GR1 = new GUIReserver(3);
me.t3 = new Thread(GR1);
me.t3.start();
}
}
One major problem: Your Squares JPanels preferred size is only 20 by 20, and will likely actually be that size since it seems to be added to a FlowLayout-using container. Next you seem to be drawing at locations that are well beyond the bounds of this component, and so the drawings likely will never be seen. Consider allowing your Squares objects to be larger, and make sure to only draw within the bounds of this component.
Note also there is code that doesn't make sense, including:
private int myID;
private JTextField row, column, instru draft saved // ???
package question2;ction1, instruction2, seatLabel, rowLabel; // ???
I'm guessing that it's
private int myID;
private JTextField row, column, instruction1, instruction2, seatLabel, rowLabel;
And this won't compile for us:
int rows = AircraftSeatReservation.getRows();
int seatsInRow = AircraftSeatReservation.getSeatsInRow(); // and shouldn't this take an int row parameter?
since we don't have your AircraftSeatReservation class (hopefully you don't really have static methods in that class).
And we can't compile or run your current code. We don't want to see your whole program, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem. So as Andrew Thompson recommends, for better help, please create and post your Minimal, Complete, and Verifiable example or Short, Self Contained, Correct Example.
I would try to OOP-ify your problem as much as possible, to allow you to divide and conquer. This could involve:
Creating a SeatClass enum, one with possibly two elements, FIRST and COACH.
Creating a non-GUI Seat class, one with several fields including possibly: int row, char seat ( such as A, B, C, D, E, F), a SeatClass field to see if it is a first class seat or coach, and a boolean reserved field that is only true if the seat is reserved.
This class would also have a getId() method that returns a String concatenation of the row number and the seat char.
Creating a non-GUI Airplane class, one that holds two arrays of Seats, one for SeatClass.FIRST or first-class seats, and one for SeatClass.COACH.
It would also have a row count field and a seat count (column count) field.
After creating all these, then work on your GUI classes.
I'd create a GUI class for Seats, perhaps GuiSeat, have it contain a Seat object, perhaps have it extend JPanel, allow it to display its own id String that it gets from its contained Seat object, have it override getBackground(...) so that it's color will depend on whether the seat is reserved or not.
etc.....

Double Static Array Throws Exception

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)

Categories

Resources