Processing 3.x not recognizing random() function - java

I'm trying to create a basic "tree" shape in processing. I have an initial constructor that takes my arguments and draws them in fixed locations on the background, but I also have a secondary constructor that is supposed to assign random values that I specify so that each time it is drawn the trees are in different locations. However, I am having an issue with Processing where it says The function random(int) does not exist and I can't seem to find a solution to the issue.
I realize this is a naive approach to graphics, but I am just trying to get my feet wet with Processing.
My Tree.java class:
import processing.core.PApplet;
import java.util.Random;
public class Tree{
// Instance variables
private int centerX, centerY;
private float scale;
private int trunkR, trunkG, trunkB, leavesR, leavesG, leavesB;
private static PApplet sketch;
public Tree(int theCenterX, int theCenterY, float theScale,
int theTrunkR, int theTrunkG, int theTrunkB,
int theLeavesR, int theLeavesG, int theLeavesB)
{
centerX = theCenterX;
centerY = theCenterY;
scale = theScale;
trunkR = theTrunkR;
trunkG = theTrunkG;
trunkB = theTrunkB;
leavesR = theLeavesR;
leavesG = theLeavesG;
leavesB = theLeavesB;
}
public Tree(){
centerX = random(960.0);
centerY = random(700.0);
scale = random(2.0);
trunkR = random(255.0);
trunkG = random(255.0);
trunkB = random(255.0);
leavesR = random(255.0);
leavesG = random(255.0);
leavesB = random(255.0);
}
public void draw(){
sketch.noStroke();
sketch.fill(trunkR, trunkG, trunkB);
sketch.rect(centerX, centerY, 80*scale, 300*scale);
sketch.fill(leavesR, leavesG, leavesB);
sketch.triangle(centerX - 40*scale, centerY + 40*scale, centerX + 40*scale, centerY - 80*scale, centerX + 120*scale, centerY + 40*scale);
}
public static void setup(PApplet theSketch){
sketch = theSketch;
}
}
And here is my main class that calls the tree class to create the objects:
Tree tree, tree2, tree3, tree4, randomTree;
void settings(){
size(1000, 1000);
}
void setup(){
setupGraphicClasses();
tree = new Tree(width/2 - 400, height/2 - 100, 1.0, 67, 12, 12, 27, 129, 28);
tree2 = new Tree(width/2 + 200, height/2 + 150, 1.5, 67, 12, 12, 27, 129, 28);
tree3 = new Tree(width/2, height/2 - 80, 0.5, 67, 12, 12, 27, 129, 28);
tree4 = new Tree(width/2 + 320, height/2 - 170, 0.9, 67, 12, 12, 27, 129, 28);
randomTree = new Tree();
}
void draw() {
background(127);
noStroke();
fill(16, 85, 17);
rect(0, 500, 1000, 500);
fill(70, 195, 255);
rect(0, 0, 1000, 500);
tree.draw();
tree4.draw();
tree2.draw();
tree3.draw();
randomTree.draw();
}
public void setupGraphicClasses() {
Tree.setup(this);
}
Why would I be getting this error? I have tried casting the instance variables as float since those are the parameters the random() function accepts as parameters, but then I get a different error message.

You're calling the random() function from your Tree class, not your sketch class. That won't work, because only the sketch class knows about the random() function.
One approach to fix this is to pass an instance of your sketch into the Tree class, then use that to get to the random function. Something like this:
void setup(){
Tree tree = new Tree(this);
}
class Tree{
public Tree(PApplet sketch){
float x = sketch.random(100);
}
}
If all you need is the random() function, this might be overkill though. You could just use the Math.random() function instead. Of course, this locks you into deploying as Java, which might be overly restrictive.

Related

Java - Trouble Passing Variables Between Main Method and Drawing Method

I'm creating a dots and boxes program and I am trying to feed the coordinate values from the main method where the user inputs them to the paintComponent method in the JFrame class. However I have to throw in the (Graphics g) parameter, and I don't see a way around it to feed in the values. It's probably big cringe because I'm still starting out but any help would be great.
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
JFrame f = new JFrame("Dots & Boxes");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Drawing a = new Drawing();
f.add(a);
f.setSize(1440,990);
f.setVisible(true);
Scanner input = new Scanner(System.in);
System.out.println("You will choose two coordinates on the dot grid to place a line between.");
System.out.println("Make sure that they are right next to each other, either vertically or horizontally (not diagonal)");
int xOne;
int yOne;
int xTwo;
int yTwo;
boolean playerOneTurn = true;
for (int i = 0; i <= 760; i++){
System.out.println("Pick Your First X-Coordinate: ");
xOne = input.nextInt();
System.out.println("Pick Your First Y-Coordinate: ");
yOne = input.nextInt();
System.out.println("Pick Your Second X-Coordinate: ");
xTwo = input.nextInt();
System.out.println("Pick Your Second Y-Coordinate: ");
yTwo = input.nextInt();
playerOneTurn = !playerOneTurn;
}
}
}
class Drawing extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.WHITE);
setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.drawString("0", 75, 45);
g.drawString("1", 110, 45);
g.drawString("2", 145, 45);
g.drawString("3", 180, 45);
g.drawString("4", 215, 45);
g.drawString("5", 250, 45);
g.drawString("6", 285, 45);
g.drawString("7", 320, 45);
g.drawString("8", 355, 45);
g.drawString("9", 390, 45);
g.drawString("10", 417, 45);
g.drawString("11", 452, 45);
g.drawString("12", 487, 45);
g.drawString("13", 522, 45);
g.drawString("14", 557, 45);
g.drawString("15", 592, 45);
g.drawString("16", 627, 45);
g.drawString("17", 662, 45);
g.drawString("18", 697, 45);
g.drawString("19", 732, 45);
g.drawString("0", 40, 75);
g.drawString("1", 40, 110);
g.drawString("2", 40, 145);
g.drawString("3", 40, 180);
g.drawString("4", 40, 215);
g.drawString("5", 40, 250);
g.drawString("6", 40, 285);
g.drawString("7", 40, 320);
g.drawString("8", 40, 355);
g.drawString("9", 40, 390);
g.drawString("10", 35, 425);
g.drawString("11", 35, 460);
g.drawString("12", 35, 495);
g.drawString("13", 35, 530);
g.drawString("14", 35, 565);
g.drawString("15", 35, 600);
g.drawString("16", 35, 635);
g.drawString("17", 35, 670);
g.drawString("18", 35, 705);
g.drawString("19", 35, 740);
int dotx1 = 80;
int doty1 = 70;
((Graphics2D) g).setStroke(new BasicStroke(5));
for (int h = 0; h <= 19; h++) {
for (int i = 0; i <= 19; i++) {
g.drawLine(dotx1, doty1, dotx1, doty1);
dotx1 = dotx1 + 35;
}
dotx1 = 80;
doty1 = doty1 + 35;
}
}
}
You shouldn't call paintComponent by yourself. The method is called when Java is drawing the window.
The reason is that the user shouldn't care about re-drawing, most of the time. Java will decide when to redraw, for example on window minimize/maximize or resizing or when an element is clicked.
To draw animated shapes you must ask Java to redraw your window. You can add f.revalidate() to force components to redraw. Take a look at the documentation here.
Be really careful when using this. Never call this inside a loop without waiting between frames, because your CPU will go crazy if not !
If you want animated shapes, call revalidate() at fixed rate, for example 60fps.
In your case, you could simple put your Scanner inside the loop, ask the user for input, process it and then redraw the window.
Also, revalidate() is not blocking, it will just tell Java that the components tree has changed and must be redraw. But it will do it when he will have the time to do it.
Edit : As we are discussing in commentary, to feed your Drawing with the data to draw you must give him the informations.
First, create your graphical elements, let start with points :
class Point {
public float x, y;
Point(float x, float y) {
this.x = x;
this.y = y;
}
}
In your Drawing (who is in fact your Scene, let rename it), add setters and List
class Scene {
private List<Point> mPoints = new LinkedList<Point>();
public addPoint(Point p) {
mPoints.add(p);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
....
for (Point p : mPoints) {
// draw your points here
}
....
}
}
There several way to improve this simple example. First, you could add a paint(Graphics g) method on Point class.
When you will add another kind of component, you should create a base class Item and extend it in your graphical items (Point, Box...) and put the paint method in this new base class.
It's the way to don't have one list for each kind of element, and then you can just iterate over items and call paint without worrying about the kind behind it (Point, Box...)

Experiencing issues drawing layered graphics

I have an open ended school project and I am attempting something somewhat intricate but I am having issues when it come to drawing the graphic layers properly.
I am trying to drawArc recursive spirals on top of fillOval recursive Concentric circles. I have moved the recursive call for fillOval both before and after the recursive calls for the spirals and it hasn't changed the end effect where the spirals aren't even created. But if I use drawOval the concentric circles appear overlapping with the spirals.
My Code is displayed below:
I am currently using BlueJ as that is the designated program for my class.
` import java.awt.;
import javax.swing.;
public class DrawPicture extends JApplet
{
// instance variables - replace the example below with your own
private final int SIZE = 600;
private final int DIST = 20;
private final int DELTA = 1;
public int i = 1;
public void recCirc(int xy, Graphics page, int clr)
{
if(xy <= SIZE/2)
{
if(clr%2 == 0)
page.setColor(Color.magenta);
else
page.setColor(Color.green);
}
page.drawOval(xy, xy, SIZE-2*xy, SIZE-2*xy);
recCirc(xy + DIST, page, clr+1);
}
public void drawRec(int xy, int angle, Graphics page)
{
if(angle < 360*2)
{
page.drawArc(xy, xy, SIZE-2*xy, SIZE-2*xy, angle, DELTA);
drawRec(xy+DELTA, angle + DELTA, page);
}
}
public void paint(Graphics page)
{
page.setColor(Color.blue);
drawRec(0, 0, page);
page.setColor(Color.red);
drawRec(0, 45, page);
page.setColor(Color.blue);
drawRec(0, 90, page);
page.setColor(Color.red);
drawRec(0, 135, page);
page.setColor(Color.blue);
drawRec(0, 180, page);
page.setColor(Color.red);
drawRec(0, 225, page);
page.setColor(Color.blue);
drawRec(0, 270, page);
page.setColor(Color.red);
drawRec(0, 315, page);
recCirc(0, page, 0);
}
}`
As a secondary but not necessary answer, if someone would know how to use fillArc and I guess with a decreasing radius make it so the arc's drew correctly and made a proper filled spiral design I'd be intrested in the answer,.. I can only imagine it must use some form of decreasing radius to do it,.. darned if I can puzzle it out.
Thank you in advance for any insight given.

How can I recreate my graphic using recursion?

I have a graphic which consists of a horizontal line of circles of different sizes at regular intervals. Here is the picture:
I am trying to recreate this graphic using recursion as opposed to the if statements used in my code but after trying, am unsure about how to do this. Would love some help, here is my code:
package weekFour;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.*;
#SuppressWarnings("serial")
public class Circle extends JPanel {
private int circX = 10;
private static int windowW = 1700;
private static int windowH = 1000;
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //smoothes out edges
Color c5 = new Color(50, 50, 50);
Color c4 = new Color(100, 100, 100);
Color c3 = new Color(150, 150, 150);
Color c2 = new Color(200, 200, 200);
Color c1= new Color(250, 250, 250);
for (int i = 0; i < 1; i++) {
g2.setColor(c1);
g2.fillOval(522 + 75*i, 138, 666, 666);
g2.setColor(c1);
g2.drawOval(522 + 75*i, 138, 666, 666);
}
for (int i = 0; i < 3; i++) {
g2.setColor(c2);
g2.fillOval(244 + 522*i, 365, 180, 180);
g2.setColor(c2);
g2.drawOval(244 + 522*i, 365, 180, 180);
}
for (int i = 0; i < 10; i++) {
g2.setColor(c3);
g2.fillOval(130 + 174*i, 428, 60, 60);
g2.setColor(c3);
g2.drawOval(130 + 174*i, 428, 60, 60);
}
for (int i = 0; i < 25; i++) {
g2.setColor(c4);
g2.fillOval(60 + 87*i, 444, 25, 25);
g2.setColor(c4);
g2.drawOval(60 + 87*i, 444, 25, 25);
}
for (int i = 0; i < 120; i++) {
g2.setColor(c5);
g2.fillOval(circX + 29*i, 450, 12, 12);
g2.setColor(c5);
g2.drawOval(circX + 29*i, 450, 12, 12);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MyTaskToo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new Circle());
frame.setSize(windowW, windowH);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Thanks for your time.
This is how I went about this problem, although we had to do it with green circles as opposed to grey circles but it's not that different.
N.B: Sorry for the appealing comments for sometimes trivial things but we get marks for commenting and it is better to be safe than sorry. Maybe they change you some insight into the thought process.
Here is the main method that starts the programme and sets out the window information.
public class Q2Main {
public static void main(String[] args) {
// here we are just setting out the window end putting the circles drawin in Q2Circles into this window.
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(1000, 500);
window.getContentPane().add(new Q2Circles(5));
window.setVisible(true);
}}
This is where the magic happens:
public class Q2Circles extends JPanel {
// this allows the user to specify how many loops of recursion they want the programme to complete before finishing
int recursionsToDo;
public Q2Circles(int recursionMax){
super();
recursionsToDo = recursionMax;
}
/*
this method is automatically called when we run the constructor as it inherits from the JFram superclass. here
we are setting out the size of the circle by getting the size of the window to make it proportional to the rest
of the screen and circles.
we then pass these values into the drawCircle method to draw the circle
*/
public void paintComponent(Graphics g){
Rectangle rectangle = this.getBounds();
int diameter = rectangle.width/3;
int centerPoint = rectangle.width/2;
drawCircle(g, 1, centerPoint, diameter);
}
/*
This method is where the magic of the programme really takes place. first of all we make sure we haven't completed
the necessary recursions. we the set the color by dividing it by the amount of times we have recursed, this will
have the affect of getting darker the more times the method recurses. we then sset the color. finaly we fill the
oval (draw the circle). because we want to move depending on the times it has recursed and size of the previous
we do it based on the size of the elements from the previous call to this method. Getting the right numbers
though was just alot of trial and error.
we then increment the recursion counter so that we know how many times we have recursed and that can then be
used at different points where needed. e.g for setting the color.
each recursive call used the dimension of the other recursive calls to make the whole picture. Although the
first recursive call creates the circles on the right of the screen. the second call draws the circle on the
left of the screen and the last one does the circles in the middle, they all use eachothers values to make it
complete. without one recursive step, more is missing than just what is created by that recursive call on its own.
in all honesty though, there is alot of duplication, like the large middlecircle.
*/
public void drawCircle(Graphics g, int amountOfRecursions, int center, int diameter){
if (amountOfRecursions <= recursionsToDo){
int recursionsCount = amountOfRecursions;
int greenColor = Math.round(225 / (amountOfRecursions));
g.setColor(new Color(0, greenColor, 0));
g.fillOval(center - (diameter/2), 200 - (diameter/2), diameter, diameter);
recursionsCount++;
drawCircle(g, recursionsCount, Math.round(center + diameter), diameter/3);
drawCircle(g, recursionsCount, Math.round(center - diameter), diameter/3);
drawCircle(g, recursionsCount, Math.round(center), diameter/3);
}
}}

How do I get text to display over a graphic?

I'm new to Java so thank you for your time and help!
Basically I want to get text to display over a graphic I have created. Basically I made a trophy and want it to display "#1" on it.
Can anyone please help me with how to do this? Thank you again
Below is the code I have written so far. You can see that the position for the "#1" is all set and done but it's appearing behind the graphic.
import javax.swing.JApplet;
import java.awt.*;
import java.net.*;
import javax.imageio.*;
import java.io.*;
import java.awt.Graphics2D;
public class BusinessCard extends JApplet
{
/**
* Paint method for applet.
*
* #param g the Graphics object for this applet
*/
public void paint(Graphics page)
{
//Variables used in rectangle
int x = 0;
int y = 0;
int width = 500;
int height = 300;
page.drawRect(x, y, width, height); //draws the rectangle using variables
//Displays name
Font f = new Font("Helvetica", Font.BOLD, 26);
page.setFont(f);
page.drawString ("anonymous", 300,100);
//Displays company
Font g = new Font("Helvetica", Font.PLAIN, 18);
page.setFont(g);
page.drawString ("blank", 320, 120);
//Displays email
Font h = new Font("Helvetica", Font.PLAIN, 15);
page.setFont(h);
page.drawString ("email", 315,140);
//int for the logo
final int MID = 350;
final int TOP = 168;
setBackground (Color.yellow); //Revisit. For some reason it only turns yellow after you resize the window
Font i = new Font("Helvetica", Font.BOLD, 16);
page.setFont(i);
page.drawString ("#1", MID+20, TOP+20);
page.setColor (Color.orange);
page.fillOval (MID, TOP, 60, 60); //bottom half of the trophy. the rounded part.
page.drawArc (MID-8, TOP+15, 25, 25, 100, 160); //left arc
page.drawArc (MID+43, TOP+15 , 25, 25, 280, 160); //right arc
page.fillRect (MID+1, TOP+1, 59, 25); //make the top of the trophy flat basically
page.fillRect (MID+22, TOP+60, 15, 25); //neck of the trophy
page.drawLine (MID+48, TOP+84, MID+10, TOP+84); //base of the trophy
}
I think you have to draw the trophy first and then write the text!
Whatever you draw appears on the top layer of the control.
First, do what sabre_raider said. You do want it before, but something else must be fixed too
You're drawing orange on orange. You draw the trophy, then set the background of your page to be yellow, then draw the "#1" in orange again. Change setBackground to page.setColor to draw in yellow (which appears to be what you want). setBackground sets the background of the applet, which im assuming is not what you want, but rather to draw the "#1" in yellow. If you did mean to set the background, make sure to do that in Applet's init method!! Not each time you repaint. (Along with that, in init, have setSize(500, 300) to properly size the window to the size of your message)
Also, I recomend splitting that up into different methods, as that will just make it more readable. Here's what your methods should look like in general:
/**
* Paint method for applet.
*
* #param g
* the Graphics object for this applet
*/
public void paint(Graphics page)
{
drawBorder( page );
drawText( page );
drawTrophy( page, 1 );
}
private void drawBorder(Graphics page) {
int x = 0;
int y = 0;
int width = 500;
int height = 300;
page.setColor( Color.black );
page.drawRect( x, y, width, height );
}
private void drawText(Graphics page) {
// Displays name
Font f = new Font( "Helvetica", Font.BOLD, 26 );
page.setFont( f );
page.drawString( "anonymous", 300, 100 );
// Displays company
Font g = new Font( "Helvetica", Font.PLAIN, 18 );
page.setFont( g );
page.drawString( "blank", 320, 120 );
// Displays email
Font h = new Font( "Helvetica", Font.PLAIN, 15 );
page.setFont( h );
page.drawString( "email", 315, 140 );
}
private void drawTrophy(Graphics page, int number) {
final int MID = 350;
final int TOP = 168;
page.setColor( Color.orange );
page.fillOval( MID, TOP, 60, 60 ); // bottom half of the trophy. the rounded part.
page.drawArc( MID - 8, TOP + 15, 25, 25, 100, 160 ); // left arc
page.drawArc( MID + 43, TOP + 15, 25, 25, 280, 160 ); // right arc
page.fillRect( MID + 1, TOP + 1, 59, 25 ); // make the top of the trophy flat basically
page.fillRect( MID + 22, TOP + 60, 15, 25 ); // neck of the trophy
page.drawLine( MID + 48, TOP + 84, MID + 10, TOP + 84 ); // base of the trophy
Font i = new Font( "Helvetica", Font.BOLD, 16 );
page.setColor( Color.yellow );
page.setFont( i );
page.drawString( "#" + number, MID + 20, TOP + 20 );
}
Firstly, I wouldn't paint directly onto a top level container. I'd use something like a JPanel to do my custom painting and then add that to the top level container.
Secondly, you should avoid overriding paint where possible. If you use a custom component as suggested in the first point, you should use paintComponent instead.
Thirdly, ALWAYS call super.paint (or super.paintComponent if you're using a custom component).
Fourthly, ever body else is right. You should be trying to draw you text AFTER the graphics...
This is the code I used:
public class BusinessCard extends JApplet {
/**
* Paint method for applet.
*
* #param g the Graphics object for this applet
*/
public void paint(Graphics page) {
super.paint(page);
//Variables used in rectangle
int x = 0;
int y = 0;
int width = 500;
int height = 300;
page.drawRect(x, y, width, height); //draws the rectangle using variables
//int for the logo
final int MID = 350;
final int TOP = 168;
page.setColor(Color.orange);
page.fillOval(MID, TOP, 60, 60); //bottom half of the trophy. the rounded part.
page.drawArc(MID - 8, TOP + 15, 25, 25, 100, 160); //left arc
page.drawArc(MID + 43, TOP + 15, 25, 25, 280, 160); //right arc
page.fillRect(MID + 1, TOP + 1, 59, 25); //make the top of the trophy flat basically
page.fillRect(MID + 22, TOP + 60, 15, 25); //neck of the trophy
page.drawLine(MID + 48, TOP + 84, MID + 10, TOP + 84); //base of the trophy
page.setColor(Color.yellow); //Revisit. For some reason it only turns yellow after you resize the window
Font font = UIManager.getFont("Label.font");
page.setFont(font.deriveFont(Font.BOLD, 16));
page.drawString("#1", MID + 20, TOP + 20);
//Displays name
page.setFont(font.deriveFont(Font.BOLD, 26));
page.drawString("anonymous", 300, 100);
//Displays company
page.setFont(font.deriveFont(Font.PLAIN, 18));
page.drawString("blank", 320, 120);
//Displays email
page.setFont(font.deriveFont(Font.PLAIN, 15));
page.drawString("email", 315, 140);
}
}
And it produced
Beware, that everybody may have the font you're trying to use installed (you code caused the applet to crash)

Rotated shapes not appearing on an Applet

I'm making a Pinball style applet and I ran into some problems before that have thankfully been remedied. However, I've hit another stumbling block.
To draw flippers for the pinball machine, I intended to draw an angled rounded rectangle which would allow me to possibly animate it later on so that you could see it moving up when I add threads to the applet. This is all done in the Table's paintComponent method. When I don't apply any rotation to check that it's all working ok, it draws the shape fine. But when I apply a rotation (whether through an Affine Transform object as in my code now or the Graphics2D.rotate method) the shape does not draw for some reason. I'm not sure why but I'm hoping that I've merely overlooked something. I have looked around online, but either I'm not putting in the right keywords or it is simply that I'm overlooking something.
The code for my Pinball and Table classes is below, please feel free to point out anything that you think could cause this strangeness. Note that I haven't given the right coordinates exactly yet as I can tweek it's position when it's drawn and I can see it, in case any of you run any similar code to try and debug it.
As a P.S. Would calling the ball's constructor on table be a better idea than doing it on the applet? Just wondering if what I've done with that is really inefficient.
import javax.swing.*; // useful for the drawing side, also going to be a JApplet
import java.awt.*;
import java.net.*;
public class Pinball extends JApplet
{
// variables go here
Table table;
Player player;
Ball ball;
Miosoft miosoft;
Miofresh miofresh;
Mioboost mioboost;
Miocare miocare;
Miowipe miowipe;
// further initialisation of the GUI
public void init()
{
setSize(300, 300);
table = new Table(this);
player = new Player();
ball = new Ball(180, 175); // set the ball's initial position in the arguments
miosoft = new Miosoft();
miocare = new Miocare();
miowipe = new Miowipe();
miofresh = new Miofresh();
mioboost = new Mioboost();
setContentPane(table); // makes our graphical JPanel container the content pane for the Applet
// createGUI(); // this has been moved onto the table class
}
public void stop()
{
}
// little getters to make things easier on the table
public int getBallX()
{
return ball.getXPosition();
}
public int getBallY()
{
return ball.getYPosition();
}
public int getLives()
{
return player.getLives();
}
public int getScore()
{
return player.getScore();
}
}
And here is the table class
import java.awt.*; // needed for old style graphics stuff
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.*; // gives us swing stuff
import sun.rmi.transport.LiveRef;
import java.io.IOException;
import java.net.*; // useful for anything using URLs
/*--------------------------------------------------------------
Auto-generated Java code for class Table
Generated by QSEE-SuperLite multi-CASE, QSEE-Technologies Ltd
www.qsee-technologies.com
Further developed to be the Content pane of this application by Craig Brett
----------------------------------------------------------------*/
public class Table extends JPanel
{
// attributes go here
Pinball pb;
Color bgColour;
Color launcherColour;
Color ballColour;
Image logo;
Image freshBonus;
Image midCircle;
Image leftBumper;
Image rightBumper;
Image nappy1;
Image nappy2;
Image nappy3;
int ballX;
int ballY;
int playerLives;
int playerScore;
// constructor goes here
public Table(Pinball pb)
{
setPreferredSize(new Dimension(300, 300));
this.pb = pb;
// this is not needed anymore, with the new loadImage class down the bottom
// Toolkit tk = Toolkit.getDefaultToolkit(); // needed to get images
// logo = tk.getImage(base + "images/bambinomio.jpg");
logo = loadImage("bambinomio.jpg");
freshBonus = loadImage("miofresh circle.jpg");
midCircle = loadImage("middle circle.jpg");
leftBumper = loadImage("left bumper.jpg");
rightBumper = loadImage("right bumper.jpg");
nappy1 = loadImage("nappy1.jpg");
nappy2 = loadImage("nappy2.jpg");
nappy3 = loadImage("nappy3.jpg");
createGUI();
}
// public methods go here
// all GUI creation stuff goes here
public void createGUI()
{
// setting the background colour
bgColour = new Color(190, 186, 221); // makes the sky blue colour for the background.
setBackground(bgColour);
launcherColour = new Color(130, 128, 193);
ballColour = new Color(220, 220, 220); // the color of the launch spring and ball
// setOpaque(false);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
// to give us access to the 2D graphics features
Graphics2D g2d = (Graphics2D) g;
// creating the panels
g2d.setColor(Color.WHITE);
g2d.fillRect(200, 20, 100, 280); // the logo Panel
g2d.fillRect(0, 0, 300, 20);
g2d.setColor(Color.BLACK);
g2d.drawRoundRect(230, 125, 40, 120, 20, 20); // the lives panel
g2d.drawRoundRect(210, 255, 80, 40, 20, 20);
g2d.drawString("Score", 215, 270);
g2d.drawString(displayScore(), 215, 290);
// now drawing the graphics
g2d.drawImage(logo, 205, 25, 90, 90, null);
g2d.drawImage(freshBonus, 10, 40, 20, 20, this);
g2d.drawImage(leftBumper, 40, 200, 10, 20, this);
g2d.drawImage(rightBumper, 150, 200, 10, 20, this);
// now the three mid circles
g2d.drawImage(midCircle, 55, 120, 25, 25, this);
g2d.drawImage(midCircle, 95, 90, 25, 25, this);
g2d.drawImage(midCircle, 95, 150, 25, 25, this);
// now filling out the lives depending on how many the players have
playerLives = pb.getLives();
if(playerLives >= 1)
g2d.drawImage(nappy1, 235, 135, 32, 30, this);
if(playerLives >= 2)
g2d.drawImage(nappy2, 235, 170, 32, 30, this);
if(playerLives >= 3)
g2d.drawImage(nappy3, 235, 205, 32, 30, this);
// now to handle the white lines
g2d.setColor(Color.WHITE);
g2d.drawLine(20, 250, 20, 60); // the left edge
g2d.drawArc(10, 40, 20, 20, 45, 225); // the top left corner
g2d.drawLine(28, 43, 160, 43); // the top of the table
g2d.drawArc(150, 41, 40, 30, 0, 120); // the top right corner
g2d.drawLine(20, 250, 35, 270); // the bottom left corner
// now for the launcher, we draw here
g2d.setColor(launcherColour);
g2d.fillRoundRect(170, 75, 30, 175, 20, 20); // the blue tube
g2d.setColor(ballColour);
g2d.fillRoundRect(175, 210, 20, 40, 20, 20); // the first bit of the launcher
g2d.fillRect(175, 210, 20, 20); // the top of the launcher's firer
g2d.fillRoundRect(175, 195, 20, 10, 20, 20); // the bit that hits the ball
// now drawing the ball wherever it is
ballX = pb.getBallX();
ballY = pb.getBallY();
g2d.fillOval(ballX, ballY, 10, 10);
// now the flippers
g2d.setPaint(Color.WHITE);
// more precise coordinates can be given when the transformation below works
// RoundRectangle2D leftFlipper = new RoundRectangle2D.Double(43.0, 245.0, 20.0, 50.0, 30.0, 30.0); // have to make this using shape parameters
// now using Affine Transformation to rotate the rectangles for the flippers
AffineTransform originalTransform = g2d.getTransform();
AffineTransform transform = AffineTransform.getRotateInstance(Math.toRadians(120));
g2d.transform(transform); // apply the transform
g2d.fillRoundRect(33, 260, 20, 40, 10, 10);
g2d.setTransform(originalTransform); // resetting the angle
// g2d.drawString("The flipper should be drawn", 80, 130); // for debugging if the previous draw instructions have been carried out
}
// a little useful method for handling loading of images and stuff
public BufferedImage loadImage(String filename)
{
BufferedImage image = null;
try
{
URL url = new URL(pb.getCodeBase(), "images/" + filename);
image = ImageIO.read(url);
}catch(IOException e)
{
System.out.println("Error loading image - " + filename + ".");
}
return image;
}
private String displayScore()
{
playerScore = pb.getScore();
String scoreString = Integer.toString(playerScore);
String returnString = "";
if(scoreString.length() < 8)
{
for(int i = 0; i < (8 - scoreString.length()); i++)
{
returnString = returnString + "0";
}
}
returnString = returnString + scoreString;
return returnString;
}
}
Normally to rotate something, you rotate it around some point of interest (the anchor point of the thing that is rotating), not the point 0,0. It appears you are rotating around 0, 0 so chances are this is getting rotated off the screen. To rotate around an arbitrary point, first translate that point to 0 (negative translation) then rotate, then do translate back (postive translation).

Categories