I'm trying to make a program that shows inheritance and polymorphism. The program is supposed to show a flag (specifically, the flag of Guinea).
This is the code:
import java.awt.*;
import javax.swing.*;
public class FlagB extends JPanel
{
public void paint (Graphics g)
{
Flag Guinea = new Flag(50,290,560);
Guinea.drawFlag(g);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Bolivian Flag");
frame.add(new FlagB());
frame.setSize(1000,725);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class Flag
{
private FlagBase fb;
private FitRect rp; //rp for rectangle parameters
private LeftTriColor lt;
private MiddleTriColor mt;
private RightTriColor rt;
private int x;
private int y;
private int z;
public Flag(int x,int y,int z)
{
this.x = x;
this.y = y;
this.z = z;
fb = new FlagBase();
rp = new FitRect(x,y,z);
lt = new LeftTriColor(x,y,z);
mt = new MiddleTriColor(x,y,z);
rt = new RightTriColor(x,y,z);
}
public void drawFlag(Graphics g)
{
fb.FlagBase(g);
lt.drawRect(g);
mt.drawRect(g);
rt.drawRect(g);
}
}
class FlagBase // The outline of the flag
{
public void FlagBase(Graphics g)
{
g.setColor(Color.BLACK);
g.drawRect(49,49,876,562);
}
}
class FitRect
{
protected int l;
protected int length;
protected int width;
public FitRect(int x,int y,int z)
{
x = l;
y = length;
z = width;
}
}
class LeftTriColor extends FitRect
{
public LeftTriColor(int x,int y,int z)
{
super(x,y,z);
}
public void drawRect(Graphics g)
{
g.setColor(Color.RED);
g.fillRect(l,l,length,width);
}
}
class MiddleTriColor extends FitRect
{
public MiddleTriColor(int x,int y,int z)
{
super(x,y,z);
}
public void drawRect(Graphics g)
{
g.setColor(Color.YELLOW);
g.fillRect(l+length+1,l,length,width);
}
}
class RightTriColor extends FitRect
{
public RightTriColor(int x,int y,int z)
{
super(x,y,z);
}
public void drawRect(Graphics g)
{
g.setColor(Color.GREEN);
g.fillRect(l+2*length+3,l,length+1,width);
}
}
The only thing that shows up in the new window is the flag's outline. I think it has something to do with the argument passing of FitRect. Is that it, or is it something else?
I've been using JCreator.
This should solve it.
class FitRect
{
protected int l;
protected int length;
protected int width;
public FitRect(int x,int y,int z)
{
l = x; //was x = l
length = y; //was y = length
width = z; //was z = width
}
}
Related
I try to create a class that was similar to the famous Processing, but soon I found a problem, since in Processing there are the setup () and draw () functions, in to which it is possible to perform certain functions, such as square (10,10,50), I tried to imitate it by creating a class, in which there is a Graphics object called "gfx" to which the various figures are added. If you read this papyrus ... thank you and I put below the PFrame class (that is the one that imitates Processing) and the BohClass class which will be the test class.
package PFrame.com;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PFrame {
private JFrame frame = new JFrame();
private DPane pane = new DPane(); //DPane is a class that extends JPanel
private Graphics2D gfx;
private Color selColor = new Color(255,255,255); //selected color
private boolean fill = true; //the shapes are filled?
public int width = 200, height = 200; //starting frame dimensins
public PFrame() {
//SKY
pane.setPreferredSize(new Dimension(width,height));
//HEAD
title(); //this functions give to the frame the name of the class (in this case "BohClass")
frame.setResizable(false);
//BODY
frame.add(pane);
pane.addComponentListener(new ResizeListener());
//TAIL
size(width,height); //function that setting size
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gfx = (Graphics2D) pane.getGraphics();
pane.paint(); //DPane function
}
//--|METHODS|--//
//FRAME CONFIG
public final void size(int x, int y) {
width = x;
height = y;
pane.setPreferredSize(new Dimension(width,height));
frame.pack();
frame.setLocationRelativeTo(null);
gfx = (Graphics2D) pane.getGraphics();
}
public final void exit() {
System.exit(0);
}
public final void hide() {
frame.setVisible(false);
}
public final void show() {
frame.setVisible(true);
}
public final void location(int XY) {
frame.setLocation(XY,XY);
}
public final void location(int X, int Y) {
frame.setLocation(X,Y);
}
public final void title() {
frame.setTitle((getClass() + "").split(" ")[1]);
}
public final void title(Object title) {
frame.setTitle(title.toString());
}
public final void resizable() {
frame.setResizable(!frame.isResizable());
}
public final void resizable(boolean resizable) {
frame.setResizable(resizable);
}
//2D CONFIG
public final void fill(boolean fill) {
this.fill = fill;
}
public final void color(int RGB) {
selColor = new Color(RGB,RGB,RGB);
}
public final void color(int R, int G, int B) {
selColor = new Color(R,G,B);
}
//2D
public final void square(int X, int Y, int L) {
rect(X,Y,L,L);
}
public final void square(int X, int Y, int L, int A) {
rect(X,Y,L,L,A);
}
public final void square(int X, int Y, int L, int Ax, int Ay) {
rect(X,Y,L,L,Ax,Ay);
}
public final void rect(int X, int Y, int W, int H) {
gfx.setColor(selColor);
if(fill) gfx.fillRect(X, Y, W, H);
else gfx.drawRect(X, Y, W, H);
}
public final void rect(int X, int Y, int W, int H,int A) {
gfx.setColor(selColor);
if(fill) gfx.fillRoundRect(X, Y, W, H, A, A);
else gfx.drawRoundRect(X, Y, W, H, A, A);
}
public final void rect(int X, int Y, int W, int H,int Ax, int Ay) {
gfx.setColor(selColor);
if(fill) gfx.fillRoundRect(X, Y, W, H, Ax, Ay);
else gfx.drawRoundRect(X, Y, W, H, Ax, Ay);
}
public final void circle(int X, int Y, int d) {
ellipse(X,Y,d,d);
}
public final void ellipse(int X, int Y, int W, int H) {
gfx.setColor(selColor);
if(fill) gfx.fillOval(X, Y, W, H);
else gfx.drawOval(X, Y, W, H);
}
public final void triangle(int Ax, int Ay, int Bx, int By, int Cx, int Cy) {
gfx.setColor(selColor);
if(fill) gfx.fillPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
else gfx.drawPolygon(new Polygon(new int[] {Ax,Bx,Cx}, new int[] {Ay,By,Cy}, 3));
}
//PANEL CONFIG
public final void background(int RGB) {
pane.setBackground(new Color(RGB,RGB,RGB));
}
public final void background(int R, int G, int B) {
pane.setBackground(new Color(R,G,B));
}
public final void clear() {
gfx.clearRect(0, 0, width, height);
}
//PUBLIC METHODS
public void setup() {}
public void loop() {}
//PRIVATE CLASS PANEL
private class DPane extends JPanel {
private static final long serialVersionUID = 57423L;
public void paint() {
setup();
while(true) {
loop();
}
}
}
//LISTENERS
class ResizeListener implements ComponentListener {
public void componentResized(ComponentEvent e) {
width = pane.getWidth();
height = pane.getHeight();
}
public void componentMoved(ComponentEvent e) {}
public void componentShown(ComponentEvent e) {}
public void componentHidden(ComponentEvent e) {}
}
}
and...
import PFrame.com.*;
public class BohClass extends PFrame {
public void setup() {
size(800,600);
background(100);
}
public void loop() {
color(72,28,47);
triangle(60,10,10,60,110,60);
color(255);
square(12,12,123);
}
public static void main(String[] args) {
new BohClass();
}
}
Like others have said, you should not have a while(true) loop inside your painting function.
Shameless self-promotion: here is a tutorial on custom painting in Swing, coming from a Processing background. Basically you need to create a Timer that triggers a repaint.
So here is the code after taking the tips into account.
The map is kept being repainted, the keylistener has changed but there still seems to be a problem.
The problem again is, the little square in the upper left corner will not move, which is the desired outcome.
package schoolgamev2;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Spel {
public static void main(String[] args) {
Speelveld map = new Speelveld();
map.Speelveld();
map.GenerateMap();
}
}
class Speelveld extends JPanel {
final int rijen = 16;
final int kolommen = 16;
Speler speler = new Speler();
Loopgebied loopgebied = new Loopgebied();
Blokken blok = new Blokken();
int[][] coordinaten = new int[rijen][kolommen];
public void Speelveld() {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(this);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
setFocusable(true);
addKeyListener(new KeyListener(this));
}
//genereer map
public void GenerateMap() {
Random random = new Random();
int x;
int y;
for (y = 0; y < rijen; y++) { //scan langs y
for (x = 0; x < kolommen; x++) { //scan langs x
//selecteert type blok voor coordinaten x y
coordinaten[x][y] = random.nextInt(4);
//debugprint
}
//debugprint
}
coordinaten[0][0] = 4; //speler begint altijd links boven
coordinaten[15][15] = 5; //finish is altijd rechts onder
}
public int[][] getCoordinaten() {
return coordinaten;
}
public Speler getSpeler2() {
return speler;
}
public int getSpelerX() {
return speler.getX();
}
public int getSpelerY() {
return speler.getY();
}
public void setSpelerX(int x) {
speler.setX(x);
}
public void setSpelerY(int y) {
speler.setY(y);
}
//#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
int x;
int y;
for (y = 0; y < rijen; y++) { //scan langs y
System.out.println("");
for (x = 0; x < kolommen; x++) { //scan langs x
blok.setX(x);
blok.setY(y);
blok.setType(coordinaten[x][y]);
System.out.print(coordinaten[x][y] + " ");
switch (blok.getType()) {
case 0:
loopgebied.teken(g);
break;
case 4:
speler.teken(g);
/*case 5:
eindveld.teken(g);
break;*/
default:
break;
}
}
}
}
}
class Speler extends Blokken {
Blokken blok = new Blokken();
public void teken(Graphics g) {
g.drawRect(blok.getX(), blok.getY(), 10, 10);
}
}
class Loopgebied extends Blokken {
Blokken blok = new Blokken();
public void teken(Graphics g) {
g.drawRect(blok.getX() * size, blok.getY() * size, size, size);
}
}
class Blokken {
private static int x;
private static int y;
private static int type;
public int size = 16;
//setters voor x y en type
public void setX(int xIn) {
x = xIn;
}
public void setY(int yIn) {
y = yIn;
}
public void setType(int typeIn) {
type = typeIn;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getType() {
return type;
}
}
class KeyListener extends KeyAdapter {
private static final int SCALE = 3;
private Speelveld speelveld;
public KeyListener(Speelveld speelveld) {
this.speelveld = speelveld;
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
int deltaX = 0;
int deltaY = 0;
if (key == KeyEvent.VK_LEFT) {
deltaX = -1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_UP) {
deltaX = 0;
deltaY = -1 * SCALE;
} else if (key == KeyEvent.VK_RIGHT) {
deltaX = 1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_DOWN) {
deltaX = 0;
deltaY = 1 * SCALE;
} else {
return;
}
int x = speelveld.getSpelerX() + deltaX;
int y = speelveld.getSpelerY() + deltaY;
speelveld.setSpelerX(x);
speelveld.setSpelerY(y);
speelveld.repaint();
}
}
As mentioned in comments, you got your player, the Speler class, that extends JPanel and is wired to use a KeyListener, but note that it is not being used as a JPanel, and so the KeyListener is non-functioning, because they only work when they have been added to a visible component that has focus.
Suggestions:
Again as per comments, make Speler a non-GUI logical class. Meaning don't have it extend JPanel or any other Swing component, and certainly don't add a KeyListener to it.
Instead give it code for the player's behavior and for having the player draw itself, and that's it. What I'm suggesting is that you try to separate part of your "Model" here the player from the "View" here the Swing GUI.
Have one JPanel and only one that does drawing. Have it override paintComponent (don't forget to call the super's paintComponent within it), and have it draw each logical component by calling the logical component's draw method (public void verf(Graphics2D g2)? or public void teken(Graphics2D g2)?) within its paintComponent method.
As a general rule, you also don't want your GUI component classes, the JPanel here, directly implementing listener interfaces, such as the KeyListener, but will want to keep them separate.
Either make this drawing JPanel focusable, give it focus and add the KeyListener, a separate class, to it.
Or better, use Key Bindings as per the tutorial: Key Bindings
For example the simple [MCVE] below doesn't use a Swing Timer or change velocities, but rather it uses a KeyListener to change position of the Speler2 object using only one drawing JPanel and a KeyListener. If I were making this more robust and larger, I would use the Swing Timer, would use Key Bindings, and would change the velocities using the key bindings.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Spel2 {
private static final int VELD_WIDTH = 500;
private static void createAndShowGui() {
Speelveld2 speelveld2 = new Speelveld2(VELD_WIDTH, VELD_WIDTH);
JFrame frame = new JFrame("Spel2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(speelveld2);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
speelveld2.requestFocusInWindow();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class MyKeyListener extends KeyAdapter {
private static final int SCALE = 3;
private Speelveld2 speelveld2;
public MyKeyListener(Speelveld2 speelveld2) {
this.speelveld2 = speelveld2;
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
int deltaX = 0;
int deltaY = 0;
if (key == KeyEvent.VK_LEFT) {
deltaX = -1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_UP) {
deltaX = 0;
deltaY = -1 * SCALE;
} else if (key == KeyEvent.VK_RIGHT) {
deltaX = 1 * SCALE;
deltaY = 0;
} else if (key == KeyEvent.VK_DOWN) {
deltaX = 0;
deltaY = 1 * SCALE;
} else {
return;
}
int x = speelveld2.getSpelerX() + deltaX;
int y = speelveld2.getSpelerY() + deltaY;
speelveld2.setSpelerX(x);
speelveld2.setSpelerY(y);
speelveld2.repaint();
}
}
#SuppressWarnings("serial")
class Speelveld2 extends JPanel {
private int prefW;
private int prefH;
private Speler2 speler2 = new Speler2();
public Speelveld2(int prefW, int prefH) {
this.prefW = prefW;
this.prefH = prefH;
setFocusable(true);
addKeyListener(new MyKeyListener(this));
}
public Speler2 getSpeler2() {
return speler2;
}
public int getSpelerX() {
return speler2.getX();
}
public int getSpelerY() {
return speler2.getY();
}
public void setSpelerX(int x) {
speler2.setX(x);
}
public void setSpelerY(int y) {
speler2.setY(y);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
speler2.teken(g2);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(prefW, prefH);
}
}
class Speler2 extends Blokken2 {
private static final int RECT_W = 10;
public Speler2() {
super(BlokkenType.SPELER);
}
#Override
public void teken(Graphics2D g2) {
int x = getX();
int y = getY();
g2.drawRect(x, y, RECT_W, RECT_W);
}
}
class Blokken2 {
private int x;
private int y;
private int velx = 0;
private int vely = 0;
private BlokkenType type;
private BufferedImage img;
public Blokken2(BlokkenType type) {
this.type = type;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getVelx() {
return velx;
}
public void setVelx(int velx) {
this.velx = velx;
}
public int getVely() {
return vely;
}
public void setVely(int vely) {
this.vely = vely;
}
public BlokkenType getType() {
return type;
}
public void setType(BlokkenType type) {
this.type = type;
}
public void setImg(BufferedImage img) {
this.img = img;
}
public BufferedImage getImg() {
return img;
}
public void teken(Graphics2D g2) {
if (img != null) {
g2.drawImage(img, x, y, null);
}
}
}
enum BlokkenType {
LOOPGEBIED, BARRICADE, MUUR, SLEUTEN, SPELER, EINDVELD
}
Edit: your latest code has an error here:
class Speler extends Blokken {
Blokken blok = new Blokken();
public void teken(Graphics g) {
g.drawRect(blok.getX(), blok.getY(), 10, 10);
}
}
Regarding your edit:
Now when you create a Speler instance, you create TWO Blokken instances, one which is the Speler instance since it extends Blokken and the other which is contained by the Speler instance since it also has a Blokken field.
You update the x/y state of the first one, but you draw with the second one, and that's why no motion is being displayed. The solution is obvious: use one or the other but not both. Either have Speler extend Blokken or have it contain a Blokken instance but don't do both.
so i'm new in stackoverflow.
I am about to create a line, a triangle anything, but i'm just focusing on the line and in a good Object orient Programming.
So i create the class Point2D:
package draw;
/**
*
* #author Pedro
*/
public class Point2D {
private int x,y;
// Construtores
public Point2D(){
this(0,0);
}
public Point2D(int x, int y){
this.x=x;
this.y=y;
}
// Set's e Get's
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
Later i create the class line using the class point2D to get the starting point and final point
package draw;
/**
*
* #author Pedro
*/
public class Linha extends Figura{
private Point2D pinicial;
private Point2D pfinal;
//construtores
public Linha(int xinicial, int yinicial, int xfinal, int yfinal){
pinicial=new Point2D(xinicial, yinicial);
pfinal=new Point2D(xfinal, yfinal);
}
public Linha(Point2D pinicial, Point2D pfinal){
this.pinicial=pinicial;
this.pfinal=pfinal;
}
//Get's e Set's
public Point2D getPinicial() {
return pinicial;
}
public void setPinicial(Point2D pinicial) {
this.pinicial = pinicial;
}
public Point2D getPfinal() {
return pfinal;
}
public void setPfinal(Point2D pfinal) {
this.pfinal = pfinal;
}
}
And then i created a Jframe with a button called "line" and put it a panel inside the jFrame that is the place where its going to get the line draw.
The problems is ... I dont know how to draw the line or how should i cal it.
Can you help me?
simply, in your JPanel class ovverride paintComponent() method:
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g)
g.drawLine(x1, y1, x2, y2);
}
}
Where x1, y1, x2, and y2, are the cords of your line.
If you ONLY want it to draw line AFTER the button is pressed, create a global boolean variable, in your main class, and when the button is pressed, set it to true, then when you create your JPanel do:
JPanel panel = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
if (myBoolean) {
super.paintComponent(g)
g.drawLine(x1, y1, x2, y2);
}
}
}
Though the advice given in the other answer is too good, but just couldn't stop myself, from adding a word or two to the same, like, in order for the painting to take place, you need to call repaint(), from inside the actionPerformed attached to JButton.
As already stated by #camickr, the use of getPreferredSize() inside the extended class for Drawing, that will provide a valid staging area, where the drawing needs to be done. This example might can help too in this direction.
Moreover, in case you wanted to keep all the lines which have been drawn on the Board so far intact, then you can simply store them in a List and iterate on this List to draw them all again, whenever a new line is to be drawn.
A simple example is as follows:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;
public class LineExample {
private DrawingBoard board;
private JButton drawLineButton;
private Random random;
private ActionListener buttonAction = new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
int width = board.getWidth();
int height = board.getHeight();
Line line = new Line(random.nextInt(width),
random.nextInt(height),
random.nextInt(width),
random.nextInt(height));
board.setValues(line);
}
};
public LineExample() {
random = new Random();
}
private void displayGUI() {
JFrame frame = new JFrame("Drawing Lines Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
board = new DrawingBoard(400, 400);
contentPane.add(board, BorderLayout.CENTER);
drawLineButton = new JButton("LINE");
drawLineButton.addActionListener(buttonAction);
contentPane.add(drawLineButton, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
new LineExample().displayGUI();
}
};
EventQueue.invokeLater(runnable);
}
}
class DrawingBoard extends JPanel {
private int width;
private int height;
private List<Line> lines;
public DrawingBoard(int w, int h) {
width = w;
height = h;
lines = new ArrayList<Line>();
}
public void setValues(Line line) {
lines.add(line);
repaint();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (Line line : lines) {
int xs = line.getXStart();
int ys = line.getYStart();
int xe = line.getXEnd();
int ye = line.getYEnd();
g.drawLine(xs, ys, xe, ye);
}
}
}
class Line {
private Point startPoint;
private Point endPoint;
public Line(int xs, int ys, int xe, int ye) {
startPoint = new Point(xs, ys);
endPoint = new Point(xe, ye);
}
public int getXStart() {
return startPoint.getX();
}
public int getYStart() {
return startPoint.getY();
}
public int getXEnd() {
return endPoint.getX();
}
public int getYEnd() {
return endPoint.getY();
}
}
class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Snooker.paint(Snooker.java:34)
this is error what I've got.
Here is the code:
Main Class:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Snooker extends JPanel {
public static final int WIDTH = 900;
public static final int HEIGHT = 450;
public static final Color c = Color.black;
public static final int SIZE_ball = 10;
private Table table;
private Ball ball;
private Cue cue;
public Snooker() {
table = new Table(0,0,c,WIDTH,HEIGHT);
ball = new Ball(150,150,Color.RED,SIZE_ball);
}
public void paint(Graphics g) {
super.paint(g);
table.drawTableOn(g);
ball.drawBallOn(g);
cue.drawCueOn(g);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Snooker");
frame.setLayout(new BorderLayout());
frame.setSize(WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Snooker game = new Snooker();
frame.add(game);
frame.setVisible(true);
game.requestFocusInWindow();
}
}
Graphics Class:
import java.awt.Color;
import java.awt.Graphics;
public class GraphicsItem {
protected int x,y;
protected Color color;
private static final int SIZE_tableX = 900;
private static final int SIZE_Cue = 30;
public static final int R_ball = 5;
public static int CoorY = 150;
public static int CoorX = 150;
public GraphicsItem(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void moveBallBy(int dx, int dy) {
x += dx;
y += dy;
}
public void drawTableOn(Graphics g) {
g.setColor(color.BLACK);
g.fillRect(x, y, SIZE_tableX, SIZE_tableX/2);
}
public void drawBallOn(Graphics g) {
g.setColor(color.BLACK);
g.fillOval(x,y,R_ball,R_ball);
}
public void drawCueOn(Graphics g) {
g.setColor(color.BLACK);
g.drawLine(x,y,SIZE_Cue,SIZE_Cue);
}
}
Also there are 5 more classes. Cue,Ball,Table and CueBall(extends Ball), BroadCloth(extends Table) . There have just attitude of their objects.
advice to solve?
You have to initialize cue in the constructor of the class Snooker.
Your constructor should be:
public Snooker() {
table = new Table(0,0,c,WIDTH,HEIGHT);
ball = new Ball(150,150,Color.RED,SIZE_ball);
cue = new Cue( ... );
}
As it stands, cue has not been instantiated, and throws a NullPointerException when you try to access its methods.
I am creating the breakout game and its isn't running just showing the bricks and the paddle and ball. I think its in my for statements in the breakin class.I added in the paddles.getW, paddles. get Y +paddles.getH and for the next for statement I added the balls.getD.
import java.awt.*;
import java.applet.*;
public class Breakin extends Applet implements Runnable
{
/**
*
*/
private static final long serialVersionUID = 1L;
Thread k;
int rows=7;
int columns=8;
Paddle paddles=new Paddle(50,200,10,40);
Ball balls=new Ball (40,150,10);
Brick [] [] bricks =new Brick [rows][columns];
Graphics dbg;
Image dbImage;
Boolean win=false;
public void init(){
int xin=0;
int yin=-15;
for(int r=0; r<rows; r++){
yin +=15;
xin=0;
for(int c=0; c<columns; c++){
int game=(int)(Math.random()*4)+1;
switch(game){
case 1:bricks[r][c]=new Brick(xin,yin,(Color.yellow),20,10);break;
case 2:bricks[r][c]=new Brick(xin,yin,(Color.green),20,10);break;
case 3:bricks[r][c]=new Brick(xin,yin,(Color.orange),20,10);break;
case 4:bricks[r][c]=new Brick(xin,yin,(Color.red),20,10);break;
}
xin+=25;
}
}
balls.setVelocity(2, 2);
}
public void start(){
k=new Thread(this);
if(k!=null){
k.start();
}
}
public void run1 ()
{
while (true)
{
balls.updateVelocity();
paddles.updateXVelo();
if (balls.intersects(paddles.getX(),paddles.getY(),paddles.getX() + paddles.getW(),paddles.getY()+ paddles.getH()));
balls.flipX();
if(balls.getX()<0 || balls.getX()>(200-balls.getD()))
balls.flipX();
for(int r=0; r<rows; r++){
for(int c=0; c<columns; c++){
if(bricks[r][c]!=null){
if(bricks[r][c].intersects(balls.getX(),balls.getY(),balls.getX()+balls.getD(),balls.getY()+ balls.getD())){
bricks[r][c]=null;
balls.flipY();}
}
}
}
repaint();
try{
Thread.sleep(20);
}
catch(InterruptedException ex)
{
}
}
}
public void destory ()
{
k.stop();
}
public void update(Graphics g)
{
if(dbImage==null)
{
dbImage=createImage(this.getSize().width, this.getSize().height);
dbg=dbImage.getGraphics();
}
dbg.setColor(getBackground());
dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
dbg.setColor(getForeground());
paint(dbg);
g.drawImage(dbImage,0,0,this);
}
public boolean keyDown(Event e, int key)
{
if(key==Event.LEFT)
{
paddles.setVelocity(0);
if (paddles.getX()>0)
paddles.setVelocity(-3);
}
if (key==Event.RIGHT)
{
paddles.setVelocity(0);
if (paddles.getX()<200-paddles.getW())//check this out
paddles.setVelocity(3);
}
return true;
}
public boolean keyUp(Event e, int Key)
{
paddles.setVelocity(0);
return true; //check
}
public void paint(Graphics g){
for(int r=0; r<rows; r++){
for(int c=0; c<columns; c++){
if(bricks[r][c]!=null){
bricks[r][c].drawBrick(g);
}
}
}
balls.pinT(g);
paddles.showT(g);
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
Paddle.java:
import java.awt.*;
public class Paddle
{
private int x;
private int y;
private int h;
private int w;
private int xVelocity;
public Paddle (int x, int y, int h, int w){
this.x=x;
this.y=y;
this.w=w;
this.h=h;
}
public void begin(int d, int a){
if(d==1){
x+=a;
}
if (d<1){
x-=a;
}
}
public void updateXVelo(){
x+=xVelocity;
}
public void showT(Graphics g)
{
g.setColor(Color.red);
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x,y,w,h);
}
public int getH(){
return h;
}
public int getW(){
return w;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setVelocity(int x){
xVelocity=x;
}
}
Ball.java:
import java.awt.*;
public class Ball{
public int x;
public int y;
public int d;
public int yvelocity;
public int xvelocity;
public Ball (int x, int y, int d)
{
this.x=x;
this.y=y;
this.d=d;
}
public void pinT(Graphics g)
{
g.setColor(Color.green);
g.fillOval(x,y,d,d);
g.setColor(Color.black);
}
public void flipX(){
xvelocity=-xvelocity;
}
public void flipY(){
yvelocity=-yvelocity;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public int getX(){
return x;
}
public int getD(){
return d;
}
public int getY(){
return y;
}
public void setVelocity(int x, int y){
xvelocity=x;
yvelocity=y;
}
public void updateVelocity(){
y+=yvelocity;
x+=xvelocity;
}
public boolean intersects(int x1,int y1,int x2,int y2)
{
return(x2>=x)&&(x+d>=x1)&&(y2>=y)&&(y+d>=y1);
}
}
Brick.java:
import java.awt.*;
public class Brick {
private int x;
private int y;
private Color color=(Color.red);
int w;
int h;
public Brick(int x, int y, Color color, int w, int h){
this.x=x;
this.y=y;
this.color=color;
this.h=h;
this.w=w;
}
public boolean intersects(int x1, int y1, int x2, int y2)
{
return( x2>=x)&&(x+w>=x1)&&(y2>=y)&&(y+h>y1);
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public void setColor (Color color){
this.color=color;//the :
}
public void drawBrick(Graphics g){
g.setColor(color);
g.fillRect(x, y, w, h);
g.setColor(Color.black);
g.drawRect(x,y,w,h);
}
}