Question

Hi, I'm writing a Java program that prints a grid with circles and squares that have...

Hi, I'm writing a Java program that prints a grid with circles and squares that have letters in them and it is also supposed to print the toString() function to the console window each time the application runs. This toString() function is supposed to show the tile's shape, letter, and color component (or components). Could someone please review and debug my code to help me figure out why my toString() function is not working?

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JButton;

import java.awt.Container;

import java.awt.GridLayout;

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.util.Random;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Color;

import java.awt.Font;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Ellipse2D.Double;

import java.util.ArrayList;

// This class inherits what is in JPanel

class Tile extends JPanel {

private int red, green, blue, letGen, shapes;

private String [] alphabetlist = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",

"R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

private String letter;

// Getter for shapes

public int getShapes() {

return shapes;

}

// Setter for shapes

public void setShapes() {

this.shapes = shapes;

}

// Getter for letter

public int getLetter() {

return letter;

}

// Setter for letter

public void setLetter() {

this.letter = letter;

}

@Override

public String toString() {

return String.format("Tile shape: %s\nLetter in tile: %s\nColor component(s) of tile: ", shapes, letter);

}

// Constructor for the class

Tile() {

super(); // Calls super class constructor

SetRandomValues(); // Constructor to set random values

}

// This is to prevent someone from messing with your constructor

final public void SetRandomValues() {

red = GetNumberBetween(0,255); // Calling the method GetNumberBetween

green = GetNumberBetween(0,255); // Calls the method GetNumberBetween

blue = GetNumberBetween(0,255); // Calls the method GetNumberBetween

letGen = GetNumberBetween(0,25); // Generates a letter from the alphabet between A - Z

letter = alphabetlist[letGen];

shapes = GetNumberBetween(0,1);

}

// Gets a letter between two letters

private static int GetNumberBetween(int min, int max) {

Random someRandomLetter = new Random();

return min + someRandomLetter.nextInt(max-min+1); // Returns a random letter

}

public void paintComponent(Graphics g) {

super.paintComponent(g); // Calls the super class's paintComponent

int panelWidth = getWidth(); // Gets the width

int panelHeight = getHeight(); // Gets the height

g.setColor(new Color(red,green,blue)); // Sets the color to the random color we created in the code above

// 0 draws a circle

if (shapes == 0) {

Graphics2D g2d = (Graphics2D)g;

Ellipse2D.Double circle = new Ellipse2D.Double(10, 10, panelWidth-20, panelHeight-20);

g2d.fill(circle); // Fills the panel with circles in the middle

}

else {

g.fillRect(10, 10, panelWidth-20, panelHeight-20); // Fills the panel with rectangles in the middle

}

// This sets the contrasting color so we can see the text in the boxes

g.setColor(new Color(GetContrastingColor(red),GetContrastingColor(green),GetContrastingColor(blue)));

final int fontSize=10; // Sets the font size

g.setFont(new Font("Arial", Font.PLAIN, fontSize)); // Sets the font type, normal font

int stringX = (panelWidth/2)-30; // Sets the position we want to draw the font at for the x position to center the font

int stringY = (panelHeight/2)+30; // Sets the position we want to draw the font at for the y position to center the font

g.drawString(letter,stringX,stringY);

}

// Makes sure that we have a contrasting color

private static int GetContrastingColor(int colorIn) {

return ((colorIn+128)%256);

}

}

class TileFrame extends JFrame implements ActionListener {

private ArrayList<Tile> tileList; // creates a private arraylist called tilelist

// Default constructor

public TileFrame() {

setBounds(200,200,1200,800); // Sets the bounds for the JFrame/window

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Places X button on the screen so that the Frame/window closes

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JPanel buttonPanel = new JPanel();

contentPane.add(buttonPanel, BorderLayout.SOUTH); // Adds button panel to the south of the BorderLayout

JButton randomize = new JButton("Randomize!"); // Creates new "Randomize" button

buttonPanel.add(randomize); // Adds randomize to buttonPanel

randomize.addActionListener(this); // Adds ActionListener on "randomize" button - the "this" is our JFrame

JPanel lettersGridPanel = new JPanel(); // Creates a panel called lettersGridPanel - holds all letters

contentPane.add(lettersGridPanel, BorderLayout.CENTER); // Adds lettersGridPanel to the center of the BorderLayout

lettersGridPanel.setLayout(new GridLayout(10,10)); // Sets this to a 10x10 GridLayout

tileList = new ArrayList<Tile>(); // Initializes tilelist as an arraylist

// For loop which goes through this loop 100 times (creates 100 tiles, adds each of the 100 tiles to the grid)

for(int i=1; i<101; i++) {

Tile tile = new Tile(); // Creates a new Tile object

tileList.add(tile); // Adds tilelist to tile

lettersGridPanel.add(tile); // Adds lettersGridPanel to tile

}

}

public void actionPerformed(ActionEvent e) {

// When the button is pushed in tileList, we tell each item within tileList them to randomize themselves

for(Tile tile : tileList) {

tile.SetRandomValues();

}

repaint();

}

}

public class Mosaic {

public static void main(String[] args) {

System.out.println("Start paint***");

// Creates new frame

TileFrame myTileFrame = new TileFrame();

myTileFrame.setVisible(true); // Makes the frame visible

}

}

Homework Answers

Answer #1

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JButton;

import java.awt.Container;

import java.awt.GridLayout;

import java.awt.BorderLayout;

import java.awt.FlowLayout;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.util.Random;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Color;

import java.awt.Font;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Ellipse2D.Double;

import java.util.ArrayList;

// This class inherits what is in JPanel

class Tile extends JPanel {

private int red, green, blue, letGen, shapes;

private String [] alphabetlist = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",

"R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
Color cc;

private String letter;

// Getter for shapes

public int getShapes() {

return shapes;

}

// Setter for shapes

public void setShapes() {

this.shapes = shapes;

}

// Getter for letter

public String getLetter() {

return letter;

}

// Setter for letter

public void setLetter() {

this.letter = letter;

}

@Override

public String toString() {

String str;
if(shapes==0) str="Circle";
else str="Square";

//return String.format("Tile shape: %d\nLetter in tile: %s\nColor component(s) of tile: ", shapes, letter);

//Color do not stores name of the color and it is very hard to identify colors by comparing these Red, Green, Blue values.
//it is not possible to return color name. because total we have 256*256*256 (16,777,216) distinct colors may not be named colors.
//but we can return red, green and blue values of the color.
return String.format("Tile Shape:"+str+"\n Lettler in tile:"+letter+"\n Color component(s) of tile:"+cc.getRed()+" "+cc.getGreen()+" "+cc.getBlue());

}


// Constructor for the class

Tile() {

super(); // Calls super class constructor

SetRandomValues(); // Constructor to set random values

}

// This is to prevent someone from messing with your constructor

final public void SetRandomValues() {

red = GetNumberBetween(0,255); // Calling the method GetNumberBetween

green = GetNumberBetween(0,255); // Calls the method GetNumberBetween

blue = GetNumberBetween(0,255); // Calls the method GetNumberBetween

letGen = GetNumberBetween(0,25); // Generates a letter from the alphabet between A - Z

letter = alphabetlist[letGen];

shapes = GetNumberBetween(0,1);

}

// Gets a letter between two letters

private static int GetNumberBetween(int min, int max) {

Random someRandomLetter = new Random();

return min + someRandomLetter.nextInt(max-min+1); // Returns a random letter

}

public void paintComponent(Graphics g) {

super.paintComponent(g); // Calls the super class's paintComponent

int panelWidth = getWidth(); // Gets the width

int panelHeight = getHeight(); // Gets the height

// Sets the color to the random color we created in the code above

cc=new Color(red,green,blue);

g.setColor(cc);

//g.setColor(new Color(red,green,blue));


// 0 draws a circle

if (shapes == 0) {

Graphics2D g2d = (Graphics2D)g;

Ellipse2D.Double circle = new Ellipse2D.Double(10, 10, panelWidth-20, panelHeight-20);

g2d.fill(circle); // Fills the panel with circles in the middle

}

else {

g.fillRect(10, 10, panelWidth-20, panelHeight-20); // Fills the panel with rectangles in the middle

}

// This sets the contrasting color so we can see the text in the boxes

g.setColor(new Color(GetContrastingColor(red),GetContrastingColor(green),GetContrastingColor(blue)));

final int fontSize=10; // Sets the font size

g.setFont(new Font("Arial", Font.PLAIN, fontSize)); // Sets the font type, normal font

int stringX = (panelWidth/2)-30; // Sets the position we want to draw the font at for the x position to center the font

int stringY = (panelHeight/2)+30; // Sets the position we want to draw the font at for the y position to center the font

g.drawString(letter,stringX,stringY);
System.out.println(toString());

}

// Makes sure that we have a contrasting color

private static int GetContrastingColor(int colorIn) {

return ((colorIn+128)%256);

}

}

class TileFrame extends JFrame implements ActionListener {

private ArrayList<Tile> tileList; // creates a private arraylist called tilelist

// Default constructor

public TileFrame() {

setBounds(200,200,1200,800); // Sets the bounds for the JFrame/window

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Places X button on the screen so that the Frame/window closes

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JPanel buttonPanel = new JPanel();

contentPane.add(buttonPanel, BorderLayout.SOUTH); // Adds button panel to the south of the BorderLayout

JButton randomize = new JButton("Randomize!"); // Creates new "Randomize" button

buttonPanel.add(randomize); // Adds randomize to buttonPanel

randomize.addActionListener(this); // Adds ActionListener on "randomize" button - the "this" is our JFrame

JPanel lettersGridPanel = new JPanel(); // Creates a panel called lettersGridPanel - holds all letters

contentPane.add(lettersGridPanel, BorderLayout.CENTER); // Adds lettersGridPanel to the center of the BorderLayout

lettersGridPanel.setLayout(new GridLayout(10,10)); // Sets this to a 10x10 GridLayout

tileList = new ArrayList<Tile>(); // Initializes tilelist as an arraylist

// For loop which goes through this loop 100 times (creates 100 tiles, adds each of the 100 tiles to the grid)

for(int i=1; i<101; i++) {

Tile tile = new Tile(); // Creates a new Tile object

tileList.add(tile); // Adds tilelist to tile

lettersGridPanel.add(tile); // Adds lettersGridPanel to tile


}

}

public void actionPerformed(ActionEvent e) {

// When the button is pushed in tileList, we tell each item within tileList them to randomize themselves

for(Tile tile : tileList) {

tile.SetRandomValues();

}

repaint();

}

}

public class Mosaic {

public static void main(String[] args) {

System.out.println("Start paint***");


// Creates new frame

TileFrame myTileFrame = new TileFrame();

myTileFrame.setVisible(true); // Makes the frame visible

}

}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Compile and execute the application. You will discover that is has a bug in it -...
Compile and execute the application. You will discover that is has a bug in it - the filled checkbox has no effect - filled shapes are not drawn. Your first task is to debug the starter application so that it correctly draws filled shapes. The bug can be corrected with three characters at one location in the code. Java 2D introduces many new capabilities for creating unique and impressive graphics. We’ll add a small subset of these features to the...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the...
Using Java, write a program that allows the user to play the Rock-Paper-Scissors game against the computer through a user interface. The user will choose to throw Rock, Paper or Scissors and the computer will randomly select between the two. In the game, Rock beats Scissors, Scissors beats Paper, and Paper beats Rock. The program should then reveal the computer's choice and print a statement indicating if the user won, the computer won, or if it was a tie. Allow...
IN JAVA Speed Control Problem: The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated...
IN JAVA Speed Control Problem: The files SpeedControl.java and SpeedControlPanel.java contain a program (and its associated panel) with a circle that moves on the panel and rebounds from the edges. (NOTE: the program is derived from Listing 8.15 and 8.16 in the text. That program uses an image rather than a circle. You may have used it in an earlier lab on animation.) The Circle class is in the file Circle.java. Save the program to your directory and run it...
   import javax.swing.*; import java.awt.*; import java.awt.event.*; //Class that paints according to the user wish. public...
   import javax.swing.*; import java.awt.*; import java.awt.event.*; //Class that paints according to the user wish. public class RapidPrototyping extends JFrame implements MouseListener,ItemListener,ActionListener,MouseMotionListener {       //panel to hold color,shapes and thickness components    JPanel panel;    //shapes combobox    JComboBox shapes;    //color radio buttons    JRadioButton red, green, blue;    //thickness combobox    JComboBox thicknesses;    //clear button.    JButton clear;    JPanel center;       /*values of each selection*/    Color color;    int thickness;    String shape;...
Describe the following Java code. Give screenshots of the image it produces public class main{ public...
Describe the following Java code. Give screenshots of the image it produces public class main{ public static void main(String[] args{ new MyFrame(); } } import javax.swing.*; public class MyFrame extends JFrame{ MyPanel panel; MyFrame(){ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.add(panel); this.pack(); this.setLocationRelativeTo(null); this.setVisible(true); } } import java.awt.*; import.javax.swing.*; public class MyPanel extends JPanel{ //Image Image; MyPanel(){ //image=new ImageIcon("sky.png").getImage(); this.setPreferredSize(new Dimension(500,500)); } public void paint(Graphics g){ Graphics2D g2D = (Graphics2D) g; //g2D.drawImage(image,0,0,null); g2D.setPaint(Color.blue); g2D.setStroke(new BasicStroke(5)); g2D.drawLine(0,0,500,500); //g2D.setPaint(Colo.pink); //g2D.drawRect(0,0,100,200); //g2D.fillRect(0,0,100,200); //g2D.setPaint(Color.orange); //g2D.drawOval(0,0,100,100); //g2D.fillOval(0,0,100,100); //g2D.setPaint(color.red); //g2D.drawArc(0,0,100,100,0,180); //g2D.fillArc(0,0,100,100,0,180);...
Consider the following Java program. What is the superclass of "Clicker"? import java.awt.event.*; import javax.swing.*; public...
Consider the following Java program. What is the superclass of "Clicker"? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } Select one: a. ActionEvent b....
I cannot for the life of me get this program to run properly. I don't know...
I cannot for the life of me get this program to run properly. I don't know what I'm doing wrong. Could the format of my text files be the issue? Edit: The program works this way, you choose a year and a gender and then enter a name. When you press the button its should give you the ranking or popularity of the name. There are 5 files that I have to search through, named 2006.txt to 2010.txt. First the...
What is the output of the following Java program? public class Food {     static int...
What is the output of the following Java program? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { s = flavor; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         pepper.setFlavor("spicy");         System.out.println(pepper.getFlavor());     } } Select one: a. sweet b. 1 c. The program does not compile. d. 2 e. spicy...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
TO BE DONE IN JAVA Your task is to complete the AddTime program so that it...
TO BE DONE IN JAVA Your task is to complete the AddTime program so that it takes multiple sets of hours, minutes and seconds from the user in hh:mm:ss format and then computes the total time elapsed in hours, minutes and seconds. This can be done using the Time object already given to you. Tasks: Complete addTimeUnit() in AddTime so that it processes a string input in hh:mm:ss format and adds a new Time unit to the ArrayList member variable....
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT