setBackground statement not working? - java

import javax.swing.JApplet;
import java.awt.*;
public class Snowman extends JApplet {
//---------------------------------------------
// Draws a snowman.
//---------------------------------------------
public void paint (Graphics page)
{
final int MID = 150;
final int TOP = 50;
setBackground (Color.cyan);
page.setColor(Color.blue);
page.fillRect(0, 175, 300, 50); // ground
page.setColor (Color.yellow);
page.fillOval (-40, -40, 80, 80); // sun
page.setColor (Color.white);
page.fillOval (MID-20, TOP, 40, 40); // head
page.fillOval (MID-35, TOP+35, 70, 50); // upper torso
page.fillOval (MID-50, TOP+80, 100, 60); // lower torso
page.setColor (Color.black);
page.fillOval(MID-10, TOP+10, 5, 5);
page.fillOval(MID+5, TOP+10, 5, 5);
page.drawArc(MID-10, TOP+20, 20, 10, 190, 160); // smile
page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm
page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm
page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat
page.fillRect(MID-15, TOP-20, 30, 25); // top of hat
}
}
This is all the code. The setBackground is stated after I declare the two final variables, thanks in advance, I got this code from a book, "Java Software Solutions", I looked over it over and over, and no luck :/ thanks in advance :)

//<applet code='Snowman' width=300 height=200></applet>
import javax.swing.*;
import java.awt.*;
public class Snowman extends JApplet {
//---------------------------------------------
// Draws a snowman.
//---------------------------------------------
public void init() {
add(new SnowmanPanel());
validate();
}
}
class SnowmanPanel extends JPanel {
final int MID = 150;
final int TOP = 50;
SnowmanPanel() {
setBackground (Color.cyan);
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.setColor(Color.blue);
page.fillRect(0, 175, 300, 50); // ground
page.setColor (Color.yellow);
page.fillOval (-40, -40, 80, 80); // sun
page.setColor (Color.white);
page.fillOval (MID-20, TOP, 40, 40); // head
page.fillOval (MID-35, TOP+35, 70, 50); // upper torso
page.fillOval (MID-50, TOP+80, 100, 60); // lower torso
page.setColor (Color.black);
page.fillOval(MID-10, TOP+10, 5, 5);
page.fillOval(MID+5, TOP+10, 5, 5);
page.drawArc(MID-10, TOP+20, 20, 10, 190, 160); // smile
page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm
page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm
page.drawLine (MID-20, TOP+5, MID+20, TOP+5); // brim of hat
page.fillRect(MID-15, TOP-20, 30, 25); // top of hat
}
}
General advice.
Don't paint in a top-level Swing component. Instead move the custom painting into a JPanel or JComponent and paint there. For custom painting in the latter, override paintComponent(Graphics)
When doing custom painting, remember to call super.paintComponent(Graphics)
Set the color in the constructor (or init()) rather than in the paint method.
Other advice
For a static image, you can also draw it to a BufferedImage and put the image in an ImageIcon in a JLabel. Which is simpler.
If this book has rushed into creating applets, toss it away. applets are much more difficult than standard apps., and should not be attempted by newbies.

Try this code
import java.awt.*;
import javax.swing.JApplet;
public class SnowMan extends JApplet
{
public SnowMan()
{
setBackground(Color.cyan);
}
//---------------------------------------------
// Draws a snowman.
//---------------------------------------------
#Override
public void paint(Graphics page)
{
final int MID = 150;
final int TOP = 50;
page.setColor(Color.blue);
page.fillRect(0, 175, 300, 50); // ground
page.setColor(Color.yellow);
page.fillOval(-40, -40, 80, 80); // sun
page.setColor(Color.white);
page.fillOval(MID - 20, TOP, 40, 40); // head
page.fillOval(MID - 35, TOP + 35, 70, 50); // upper torso
page.fillOval(MID - 50, TOP + 80, 100, 60); // lower torso
page.setColor(Color.black);
page.fillOval(MID - 10, TOP + 10, 5, 5);
page.fillOval(MID + 5, TOP + 10, 5, 5);
page.drawArc(MID - 10, TOP + 20, 20, 10, 190, 160); // smile
page.drawLine(MID - 25, TOP + 60, MID - 50, TOP + 40); // left arm
page.drawLine(MID + 25, TOP + 60, MID + 55, TOP + 60); // right arm
page.drawLine(MID - 20, TOP + 5, MID + 20, TOP + 5); // brim of hat
page.fillRect(MID - 15, TOP - 20, 30, 25); // top of hat
}
}

setBackground (Color.cyan);
It is working properly in my IDE. I also changed the color of background.It works nice and properly. No need to change the code.Make sure when you are creating the class.

The paint(Graphics) method is used only to paint the parameter (in your case page).
The application applet background color has already been processed by this stage.
That is why you can fix the problem by setting it in the constructor:
public Snowman()
{
this.setBackground(Color.cyan);
}

I think you need to use, getContentPane().setBackground()

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...)

Drawing Rectangles in Java

I am trying to draw rectangles in Java like this picture:
I visualize the coordinates as I do at math but I come up with the rectangles turned upside down which is like this:
I know Im missing just a few things.What should I do?
(Colors will be edited)
public class BlockTower
{
public static void main(String[] args)
{
Rectangle rect1 = new Rectangle(20, 70, 40, 30);
rect1.draw();
rect1.setColor(Color.BLUE);
rect1.fill();
Rectangle rect2 = new Rectangle(60, 70, 40, 30);
rect2.draw();
rect2.setColor(Color.MAGENTA);
rect2.fill();
Rectangle rect3 = new Rectangle(100, 70, 40, 30);
rect3.draw();
rect3.setColor(Color.CYAN);
rect3.fill();
Rectangle rect4 = new Rectangle(40, 100, 40, 30);
rect4.draw();
rect4.setColor(Color.RED);
rect4.fill();
Rectangle rect5 = new Rectangle(80, 100, 40, 30);
rect5.draw();
rect5.setColor(Color.PINK);
rect5.fill();
Rectangle rect6 = new Rectangle(60, 130, 40, 30);
rect6.draw();
rect6.setColor(Color.BLUE);
rect6.fill();
//TODO finish the draft to display the six blocks
}
}
Coordinates in Swing start from Top Left. That means you have to recalculate your y-coordinates. So the bottom of your panel is actually at the current height.
If you've calculated something to be at coordinates (x,y) it now has to be at coordinates (x, height - y) instead.

Build Java applet to draw series of houses using a loop

I'm very new to Java, and find myself having a bit of trouble looping. I am to first design a simple applet to build a house, for which I have the code below:
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Polygon;
public class Houseref extends Applet
{
public void paint (Graphics page)
{
Polygon poly = new Polygon(); // Roof Polygon
poly.addPoint (50,90);
poly.addPoint (150, 50);
poly.addPoint (250, 90);
page.setColor (new Color(218,165,32)); // Custom brown color
page.fillPolygon (poly);
page.setColor (Color.black);
page.drawLine (50, 90, 150, 50); // Roof outline
page.drawLine (150, 50, 250, 90);
page.setColor (Color.yellow);
page.fillRect (50, 90, 200, 100); // House base with houseColor
page.setColor (Color.black);
page.drawRect (50, 90, 200, 100); // House outline
page.setColor (Color.black);
page.fillRect (75, 110, 30, 25); // Window 1
page.fillRect (190, 110, 30, 25); // Window 2
page.setColor (Color.blue);
page.drawLine (75, 123, 105, 123); // Window Frame 1
page.drawLine (89, 110, 89, 134);
page.fillRect (70, 110, 5, 25); // Shutter 1
page.fillRect (105, 110, 5, 25); // Shutter 2
page.drawLine (75+115, 123, 105+115, 123); // Window Frame 2
page.drawLine (89+115, 110, 89+115, 134);
page.fillRect (70+115, 110, 5, 25); // Shutter 3
page.fillRect (105+115, 110, 5, 25); // Shutter 4
page.setColor (Color.blue);
page.fillRect (130, 150, 35, 40); // Door
page.setColor (Color.red);
page.fillOval (155, 170, 4, 4); // Door knob
}
}
Now I need to create a loop that iterates 5 times, each time the new house must be in a different color and in a different location. I'm having trouble with understanding how to get an applet to loop. Any help is appreciated!
You don't loop an applet. You loop within an applet, as arg0's answer illustrates.
You've used magic numbers all through your paint method. You need to change the magic numbers to fields so you can change the variables.
The first thing you need to do is refactor your paint method so that you have lots of little methods. You should have a drawWall method, a drawRoof method, a drawDoor method, and a drawWindow method you call twice.
I'm assuming by different color houses you mean the wall should be different colors. You pass the color to the wall method you create as a parameter.
Here's a refactored drawWall method, so you can see what I'm talking about. You'll need to break up the rest of your paint method this way.
private void drawWall(Graphics page, Color color, int x, int y, int width,
int height) {
page.setColor(color);
page.fillRect(x, y, width, height); // House base with houseColor
page.setColor(Color.black);
page.drawRect(x, y, width, height); // House outline
}
The Rectangle class would be a good way to pass x, y, width, and height values to the method.
Here's a loop that iterates 5 times.
for(int i = 0; i < 5; i++){
/* Your_code_here */
}
I hope this helps, please tell me if it doesn't.

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