"AWT-EventQueue-0" error on a game trial code - java

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.

Related

Why is java copying instead of creating a new Instant When i use different variables?

I made a fairly simple code and i got into an error which confused me.
So I have a class that creates two totally different variables and creating them using the new keyword
Player playerLeft = new Player(5,150);
Player playerRight = new Player( 150,150);
Player class:
import javax.swing.*;
import java.awt.*;
public class Player extends JComponent {
private int posY;
private int posX;
public Player(int x, int y) {
posX = x;
posY = y;
//repaint();
}
public float getMovementY() {
return movementY;
}
public void setMovementY(int movementY) {
this.movementY = movementY;
}
int movementY = 0;
public void paintComponent(Graphics g) {
Graphics2D _g2 = (Graphics2D) g;
Rectangle rect = new Rectangle(posX, posY, 20, 150);
_g2.fill(rect);
}
public void setLocation(int x, int y) {
posY = y;
posX = x;
repaint();
}
public void move() {
setLocation(posX, posY + movementY);
}
}
It's probably me not knowing something about Java but for me when I try to instantiate playerRight it just overwrites player left and drawsOut playerRight only.
Here is the complete code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;
public class mainJFrame extends JFrame implements KeyListener {
int relativeTimeMillsec = 0;
Player playerLeft = new Player(5, 150);
Player playerRight = new Player(150, 150);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
relativeTimeMillsec++;
refreshTimeText(relativeTimeMillsec);
calcMovements();
}
};
//components
JLabel timeCounterLabel = new JLabel("Time: " + 0, SwingConstants.CENTER);
public mainJFrame() {
createComponents();
addKeyListener(this);
}
public void createComponents() {
this.setTitle("The title");
this.setSize(800, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
timer.scheduleAtFixedRate(task, 0, 10);
JButton testButton = new JButton("Label");
testButton.setSize(100, 25);
testButton.setLocation(this.getWidth() / 2 - testButton.getWidth() / 2, this.getHeight() / 2 - testButton.getHeight() / 2);
timeCounterLabel.setSize(200, 25);
timeCounterLabel.setLocation(this.getWidth() / 2 - timeCounterLabel.getWidth() / 2, 10);
//playerRight = new Player(this.getWidth()-45,this.getHeight()/2);
// this.add(testButton);
this.add(timeCounterLabel);
this.add(playerLeft);
this.add(playerRight);
}
public void paintComponent(Graphics g) {
{
super.repaint();
}
}
#Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_S) {
playerLeft.movementY = +2;
} else if (e.getKeyCode() == KeyEvent.VK_W) {
playerLeft.movementY = -2;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
playerRight.movementY = +2;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
playerRight.movementY = -2;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
#Override
public void keyTyped(KeyEvent e) {
}
private double calcRealRelativeTime(int _relTime) {
return relativeTimeMillsec / (double) 100;
}
private void refreshTimeText(int _relTime) {
timeCounterLabel.setText("Time: " + Math.round(calcRealRelativeTime(_relTime)));
}
private void calcMovements() {
playerLeft.move();
playerRight.move();
}
}
Understand that a JFrame's contentPane (the container that holds its components) uses BorderLayout by default, and this code:
this.add(timeCounterLabel);
this.add(playerLeft);
this.add(playerRight);
is adding all components to the same default BorderLayout.CENTER position, meaning any components added will replace components added previously.
But more importantly, yours is a common problem and stems from your having your Player class extend from a GUI component. Don't do this, as then you will have a great deal of difficulty drawing multiple Player objects and having them interact easily (as you're finding out). Instead have Player be a logical (non-component) class, and have only one class extend JPanel and do all the drawing. This class can hold Player objects, perhaps held in a collection such as an ArrayList<Player>, and then iterate through the collection within its paintComponent method.
Other issues:
Do not use java.util.Timer and java.util.TimerTask for Swing animations since these classes do not follow Swing threading rules. Use instead a javax.swing.Timer.
Learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others
If/when you do override a painting method such as paintComponent, be sure to call the super's method within your override, usually on the first line, so as not to break the painting chain. Also, use the #Override annotation before this method and any other methods that you think that you may be overriding so that the compiler catches possible errors with this.
For example (but not a complete example)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class SimpleAnimation extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 600;
private static final int TIMER_DELAY = 20;
private Player2 playerLeft = new Player2(5, 150, Color.RED);
private Player2 playerRight = new Player2(150, 150, Color.BLUE);
public SimpleAnimation() {
playerLeft.setySpeed(1);
playerRight.setySpeed(-1);
new Timer(TIMER_DELAY, new TimerListener()).start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
playerLeft.draw(g);
playerRight.draw(g);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
playerRight.move();
playerLeft.move();
repaint();
}
}
private static void createAndShowGui() {
SimpleAnimation mainPanel = new SimpleAnimation();
JFrame frame = new JFrame("SimpleAnimation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class Player2 {
private static final int RECT_WIDTH = 20;
private static final int RECT_HEIGHT = 50;
private int x;
private int y;
private int ySpeed;
private Color color;
public Player2(int x, int y, Color color) {
this.x = x;
this.y = y;
this.color = color;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setySpeed(int ySpeed) {
this.ySpeed = ySpeed;
}
public int getySpeed() {
return ySpeed;
}
public void setLocation(int x, int y) {
setX(x);
setY(y);
}
public void move() {
setLocation(x, y + ySpeed);
}
public void draw(Graphics g) {
g.setColor(color);
g.fillRect(x, y, RECT_WIDTH, RECT_HEIGHT);
}
}

JAVA mouselistener gives incorrrect x and y coordinates

Here I have two classes, one including main function. I want to draw a rectangle which moves automatically. But the starting point of rectangle is not the same as the point i clicked with mouse. I could not figure out this problem. Can you help me?
This is the first class including main function
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.*;
public class BuyuyenSuDamlalari extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(600,400);
BuyuyenSuDamlalari bsd1 = new BuyuyenSuDamlalari();
frame.setContentPane(bsd1);
BuyuyenSuDamlalariClickListener bscl = new BuyuyenSuDamlalariClickListener(bsd1);
bsd1.addMouseListener(bscl);
frame.setResizable(false);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
int x;
int y;
int radius;
int click;
public BuyuyenSuDamlalari() {
super();
setFocusable(true);
Timer zaman = new Timer(40, this); // bir saniyede 25 resim oluyor
zaman.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (click>0) {
g.drawRect(x, y, radius, radius);
}
}
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 void actionPerformed(ActionEvent arg0) {
radius++;
repaint();
}
public void setClick(int click) {
this.click = click;
}
}
This is the second class wihich includes motionListener
import java.awt.event.*;
public class BuyuyenSuDamlalariClickListener extends MouseAdapter {
private BuyuyenSuDamlalari bsd = new BuyuyenSuDamlalari();
private int x;
private int y;
public BuyuyenSuDamlalariClickListener(BuyuyenSuDamlalari bsd) {
super();
this.bsd = bsd;
}
public void mousePressed(MouseEvent e) {
if (e.getClickCount()>0) {
bsd.setX(e.getX()-25);
bsd.setY(e.getY()-25);
}
bsd.setClick(1);
}
}

Swing animation optimization

I have been working on a simple animation using a Timer on a JComponent. However, I experience incredibly choppy motion when I view the animation. What steps should I take to optimize this code?
MyAnimationFrame
import javax.swing.*;
public class MyAnimationFrame extends JFrame {
public MyAnimationFrame() {
super("My animation frame!");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new AnimationComponent(0,0,50,50));
setVisible(true);
}
public static void main(String[] args) {
MyAnimationFrame f = new MyAnimationFrame();
}
}
AnimationComponent
import javax.swing.*;
import java.awt.*;
public class AnimationComponent extends JComponent implements ActionListener {
private Timer animTimer;
private int x;
private int y;
private int xVel;
private int yVel;
private int width;
private int height;
private int oldX;
private int oldY;
public AnimationComponent(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
animTimer = new Timer(25, this);
xVel = 5;
yVel = 5;
animTimer.start();
}
#Override
public void paintComponent(Graphics g) {
g.fillOval(x,y,width,height);
}
#Override
public void actionPerformed(ActionEvent e) {
oldX = x;
oldY = y;
if(x + width > getParent().getWidth() || x < 0) {
xVel *= -1;
}
if(y + height > getParent().getHeight() || y < 0) {
yVel *= -1;
}
x += xVel;
y += yVel;
repaint();
}
}
Not sure if this matters, but I am using OpenJDK version 1.8.0_121.
Any help is appreciated.
After a wonderful discussion with Yago it occurred to me that the issue revolves around number of areas, alot comes down to the ability for Java to sync the updates with the OS and the hardware, some things you can control, some you can't.
Inspired by Yago's example and my "memory" of how the Timing Framework works, I tested you code by increasing the framerate (to 5 milliseconds, ~= 200fps) and decreasing the change delta, which gave the same results as using the Timing Framework, but which leaves you with the flexibility of your original design.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.add(new AnimationComponent(0, 0, 50, 50));
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class AnimationComponent extends JComponent implements ActionListener {
private Timer animTimer;
private int x;
private int y;
private int xVel;
private int yVel;
private int width;
private int height;
private int oldX;
private int oldY;
public AnimationComponent(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.height = height;
this.width = width;
animTimer = new Timer(5, this);
xVel = 1;
yVel = 1;
animTimer.start();
}
#Override
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON
);
g2d.setRenderingHints(hints);
g2d.fillOval(x, y, width, height);
}
#Override
public void actionPerformed(ActionEvent e) {
oldX = x;
oldY = y;
if (x + width > getParent().getWidth() || x < 0) {
xVel *= -1;
}
if (y + height > getParent().getHeight() || y < 0) {
yVel *= -1;
}
x += xVel;
y += yVel;
repaint();
}
}
}
If you need to slow down the speed more, then decrease the change delta more, this will mean you have to use doubles instead, which will lead into the Shape's API which supports double values
Which should you use? That's up to you. The Timing Framework is really great for linear animations over a period of time, where you know you want to go from one state to another. It's not so good for things like games, where the state of the object can change from my cycle to another. I'm sure you could do it, but it'd be a lot easier with a simple "main loop" concept - IMHO
Timing Framework offers a way to provide animations highly optimized which may help in this case.
MyAnimationFrame
import javax.swing.*;
public class MyAnimationFrame extends JFrame {
public MyAnimationFrame() {
super("My animation frame!");
setSize(300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new AnimationComponent(0,0,50,50));
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
MyAnimationFrame f = new MyAnimationFrame();
}
});
}
}
AnimationComponent
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.TimeUnit;
import org.jdesktop.core.animation.rendering.*;
import org.jdesktop.core.animation.timing.*;
import org.jdesktop.core.animation.timing.interpolators.*;
import org.jdesktop.swing.animation.rendering.*;
import org.jdesktop.swing.animation.timing.sources.*;
#SuppressWarnings("serial")
public class AnimationComponent extends JRendererPanel {
protected int x;
protected int y;
protected int width;
protected int height;
protected Animator xAnimator;
protected Animator yAnimator;
public AnimationComponent(int x, int y, int width, int height) {
setOpaque(true);
this.x = x;
this.y = y;
this.height = height;
this.width = width;
JRendererFactory.getDefaultRenderer(this,
new JRendererTarget<GraphicsConfiguration, Graphics2D>() {
#Override
public void renderSetup(GraphicsConfiguration gc) {
// Nothing to do
}
#Override
public void renderUpdate() {
// Nothing to do
}
#Override
public void render(Graphics2D g, int w, int h) {
Color c = g.getColor();
g.setColor(g.getBackground());
g.fillRect(0, 0, w, h);
g.setColor(c);
g.fillOval(AnimationComponent.this.x, AnimationComponent.this.y,
AnimationComponent.this.width, AnimationComponent.this.height);
}
#Override
public void renderShutdown() {
// Nothing to do
}
}, false);
this.xAnimator = new Animator.Builder(new SwingTimerTimingSource())
.addTargets(new TimingTargetAdapter() {
#Override
public void timingEvent(Animator source, double fraction) {
AnimationComponent.this.x = (int) ((getWidth() - AnimationComponent.this.width) * fraction);
}})
.setRepeatCount(Animator.INFINITE)
.setRepeatBehavior(Animator.RepeatBehavior.REVERSE)
.setInterpolator(LinearInterpolator.getInstance()).build();
this.yAnimator = new Animator.Builder(new SwingTimerTimingSource())
.addTargets(new TimingTargetAdapter() {
#Override
public void timingEvent(Animator source, double fraction) {
AnimationComponent.this.y = (int) ((getHeight() - AnimationComponent.this.height) * fraction);
}})
.setRepeatCount(Animator.INFINITE)
.setRepeatBehavior(Animator.RepeatBehavior.REVERSE)
.setInterpolator(LinearInterpolator.getInstance()).build();
addComponentListener(new ComponentAdapter() {
private int oldWidth = 0;
private int oldHeight = 0;
#Override
public void componentResized(ComponentEvent event) {
Component c = event.getComponent();
int w = c.getWidth();
int h = c.getHeight();
if (w != this.oldWidth) {
AnimationComponent.this.xAnimator.stop();
AnimationComponent.this.xAnimator = new Animator.Builder()
.copy(AnimationComponent.this.xAnimator)
.setDuration(w * 5, TimeUnit.MILLISECONDS) // Original speed was 200 px/s
.build();
AnimationComponent.this.xAnimator.start();
}
if (h != this.oldHeight) {
AnimationComponent.this.yAnimator.stop();
AnimationComponent.this.yAnimator = new Animator.Builder()
.copy(AnimationComponent.this.yAnimator)
.setDuration(h * 5, TimeUnit.MILLISECONDS) // Original speed was 200 px/s
.build();
AnimationComponent.this.yAnimator.start();
}
this.oldWidth = w;
this.oldHeight = h;
}
});
}
}
I'm getting good results but has one issue: any item you resize, the animation is reset.

Graphical object does not update as the xPosition updates

I am trying to create a planet (blue circle), and have it move when i update the x-position. Here's the main class.
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable{
public int width = 1400;
public int height = (width/16)* 9;
Dimension dim = new Dimension(width, height);
JFrame frame;
boolean running;
NewBody earth;
public Main(){
this.setPreferredSize(dim);
this.setBackground(Color.BLACK);
}
public void start(){
running = true;
Thread thread = new Thread(this, "display");
thread.start();
}
public void run(){
long startTime = System.currentTimeMillis();
double conv = Math.pow(10, 3);
while(running){
long now = System.currentTimeMillis();
if((now-startTime)/conv >= 1){
earth.incXPos();
startTime = now;
return;
}
update();
}
}
public void update(){
repaint();
}
public void stop(){
running = false;
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.BLUE);
g2d.fillOval(earth.xPos,earth.yPos, earth.radius*2, earth.radius*2);
}
public static void main(String args[]){
Main main = new Main();
main.frame = new JFrame();
main.frame.setResizable(false);
main.frame.add(main);
main.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.frame.pack();
main.frame.setVisible(true);
main.earth = new NewBody(0, 0,0, 50);
main.start();
}
}
And here is the NewBody blueprint, from which I am creating "earth"
public class NewBody {
Main main = new Main();
public int xOrigo = 1400/2;
public int yOrigo = 800/2;
public double mass;
public double velocity;
public int xPos;
public int yPos;
public double force;
public double vectorAngle;
public double fx;
public double fy;
public double acceleration;
public int radius;
public NewBody(double mass, int xPos, int yPos, int radius){
this.mass = mass;
this.xPos = xOrigo + xPos - radius;
this.yPos = yOrigo + yPos - radius;
this.radius = radius;
}
public void incXPos(){
this.xPos++;
}
The problem is that when I run the program, the blue circle just stays in the same position, where it was initialized. It just flickers extremely fast, and nothing else happens. I am quite new to coding, and I do not seem to get any error message and therefore I do not know how to proceed. I have been stuck on this for some hours now.
Do you have any ideas?
The return; statement in your run() method causes the method short circuits exit and thus quit immediately after calling incXPos() just once. This occurs even before update() is called and so repaint() is never called.
I'd do things a bit differently though:
I'd draw in a JPanel
I'd draw in its paintComponent method.
I'd use a Swing Timer instead of a Thread to do my animation loop.
I'd be sure to call the super's paintComponent(g) inside of my override.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SimpleAnimation extends JPanel {
private static final int PREF_W = 1400;
private static final int PREF_H = (PREF_W * 9) / 16; // do int mult **first**
private static final int TIMER_DELAY = 13;
private NewBody earth = new NewBody(0, 0, 0, 50);
public SimpleAnimation() {
new Timer(TIMER_DELAY, new TimerListener()).start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// to allow for smooth graphics
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.BLUE);
g2d.fillOval(earth.xPos, earth.yPos, earth.radius * 2, earth.radius * 2);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
earth.incXPos();
repaint();
}
}
private static void createAndShowGui() {
SimpleAnimation mainPanel = new SimpleAnimation();
JFrame frame = new JFrame("SimpleAnimation");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class NewBody {
// !! Main main = new Main();
public int xOrigo = 1400 / 2;
public int yOrigo = 800 / 2;
public double mass;
public double velocity;
public int xPos;
public int yPos;
public double force;
public double vectorAngle;
public double fx;
public double fy;
public double acceleration;
public int radius;
public NewBody(double mass, int xPos, int yPos, int radius) {
this.mass = mass;
this.xPos = xOrigo + xPos - radius;
this.yPos = yOrigo + yPos - radius;
this.radius = radius;
}
public void incXPos() {
this.xPos++;
}
}

What is wrong with my inheritance structure?

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
}
}

Categories