Displaying rotating fan on applet - java

As part of my programming assignment, I have to display a rotating fan in an applet.
Here is my code (class to display the fan):
import javax.swing.*;
import java.awt.*;
public class Fan extends JPanel
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public Fan()
{
this.setSize(600, 400);
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
}
class SpinFan implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 + 1) % 360;
angle2 = (angle2 + 1) % 360;
angle3 = (angle3 + 1) % 360;
angle4 = (angle4 + 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
repaint();
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
Class for further processing (right now just has instance of Fan):
import java.awt.*;
import javax.swing.*;
public class FanControl extends JPanel
{
public FanControl()
{
add(new Fan());
}
}
And finally, here is the Applet class:
import java.awt.*;
import javax.swing.*;
public class FanApplet extends JApplet
{
public FanApplet()
{
add(new FanControl());
}
}
Now I've been trying all sorts of stuff for a long time so please don't mind the extra commented out code. The Fan.java class works properly (I can see the fan spinning if I run it as an application by putting it in a frame). But I just can't get the fan to rotate in the Applet. However, if I add something like a JButton to the Applet from the Fan.java class, it works.
What am I missing out on? Is there some complications while using threads and applets, or paintComponent() and applets that I don't seem to know.
When I run the code as an application, it WORKS fine. I can see the rotating fan. Here is the code for that:
import javax.swing.*;
import java.awt.*;
public class Fan extends JPanel
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public Fan()
{
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.add(new Fan());
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
class SpinFan implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 - 1) % 360;
angle2 = (angle2 - 1) % 360;
angle3 = (angle3 - 1) % 360;
angle4 = (angle4 - 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
repaint();
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
}

while(true) .. repaint(); .. Thread.sleep(10);
This is entirely the wrong way to go about animation.
Don't block the EDT (Event Dispatch Thread) - the GUI will 'freeze' when that happens. Instead of calling Thread.sleep(n) implement a Swing Timer for repeating tasks or a SwingWorker for long running tasks. See Concurrency in Swing for more details.
The following source uses the Thread defined in code but puts the GUI updates back on the EDT.
But the real problem here is that the animation component was being added to the applet at size 0x0. By changing the layout of the parent container to BorderLayout, we can stretch it to fit the available space.
E.G.
import java.awt.*;
import javax.swing.*;
public class FanApplet extends JApplet
{
private int angle1 = -15;
private int angle2 = 75;
private int angle3 = 165;
private int angle4 = 255;
public FanApplet()
{
add(new FanControl());
}
class FanControl extends JPanel
{
public FanControl()
{
// by setting a BorderLayout and adding a component to the CENTER
// (default if no constraint specified) the child component will
// be stretched to fill the available space.
setLayout(new BorderLayout());
add(new Fan());
}
}
class Fan extends JPanel
{
public Fan()
{
//this.setSize(600, 400);
Runnable spinner = new SpinFan();
Thread thread1 = new Thread(spinner);
thread1.start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawOval(200, 150, 150, 150);
g.fillArc(210, 160, 130, 130, angle1, 30);
g.fillArc(210, 160, 130, 130, angle2, 30);
g.fillArc(210, 160, 130, 130, angle3, 30);
g.fillArc(210, 160, 130, 130, angle4, 30);
}
}
class SpinFan implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
angle1 = (angle1 + 1) % 360;
angle2 = (angle2 + 1) % 360;
angle3 = (angle3 + 1) % 360;
angle4 = (angle4 + 1) % 360;
System.out.println(angle1 + " " + angle2 + " " + angle3 + " " + angle4);
// This ensures that repaint() is called on the EDT.
Runnable r = new Runnable() {
public void run() {
repaint();
}
};
SwingUtilities.invokeLater(r);
Thread.sleep(10);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem while putting thread to sleep.");
}
}
}
}

Related

Printing a timer that updates every second into a simple game

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.Timer;
public class FinalFlappy implements ActionListener, MouseListener,
KeyListener
{
public static FinalFlappy finalFlappy;
public final int WIDTH = 800, HEIGHT = 800;
public FinalFlappyRend renderer;
public Rectangle bee;
public ArrayList<Rectangle> rect_column;
public int push, yMotion, score;
public boolean gameOver, started;
public Random rand;
public FinalFlappy()
{
JFrame jframe = new JFrame();
Timer timer = new Timer(16, this);
renderer = new FinalFlappyRend();
rand = new Random();
jframe.add(renderer);
jframe.setTitle("Flappy Bee");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(WIDTH, HEIGHT);
jframe.addMouseListener(this);
jframe.addKeyListener(this);
jframe.setResizable(false);
jframe.setVisible(true);
bee = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 40, 40);
rect_column = new ArrayList<Rectangle>();
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
timer.start();
}
public void addColumn(boolean start)
{
int space = 300;
int width = 60;
int height = 50 + rand.nextInt(300);
if (start)
{
rect_column.add(new Rectangle(WIDTH + width + rect_column.size() * 300, HEIGHT - height - 120, width, height));
rect_column.add(new Rectangle(WIDTH + width + (rect_column.size() - 1) * 300, 0, width, HEIGHT - height - space));
}
else
{
rect_column.add(new Rectangle(rect_column.get(rect_column.size() - 1).x + 600, HEIGHT - height - 120, width, height));
rect_column.add(new Rectangle(rect_column.get(rect_column.size() - 1).x, 0, width, HEIGHT - height - space));
}
}
public void jump()
{
if (gameOver)
{
bee = new Rectangle(WIDTH / 2 - 10, HEIGHT / 2 - 10, 40, 40);
rect_column.clear();
yMotion = 0;
score = 0;
addColumn(true);
addColumn(true);
addColumn(true);
addColumn(true);
gameOver = false;
}
if (!started)
{
started = true;
}
else if (!gameOver)
{
if (yMotion > 0)
{
yMotion = 0;
}
yMotion -= 10;
}
}
#Override
public void actionPerformed(ActionEvent e)
{
int speed = 10;
push++;
if (started)
{
for (int i = 0; i < rect_column.size(); i++)
{
Rectangle column = rect_column.get(i);
column.x -= speed;
}
if (push % 2 == 0 && yMotion < 15)
{
yMotion += 2;
}
for (int i = 0; i < rect_column.size(); i++)
{
Rectangle column = rect_column.get(i);
if (column.x + column.width < 0)
{
rect_column.remove(column);
if (column.y == 0)
{
addColumn(false);
}
}
}
bee.y += yMotion;
for (Rectangle column : rect_column)
{
if (column.y == 0 && bee.x + bee.width / 2 > column.x + column.width / 2 - 10 && bee.x + bee.width / 2 < column.x + column.width / 2 + 10)
{
score++;
}
if (column.intersects(bee))
{
gameOver = true;
if (bee.x <= column.x)
{
bee.x = column.x - bee.width;
}
else
{
if (column.y != 0)
{
bee.y = column.y - bee.height;
}
else if (bee.y < column.height)
{
bee.y = column.height;
}
}
}
}
if (bee.y > HEIGHT - 120 || bee.y < 0)
{
gameOver = true;
}
if (bee.y + yMotion >= HEIGHT - 120)
{
bee.y = HEIGHT - 120 - bee.height;
gameOver = true;
}
}
renderer.repaint();
}
public void paintColumn(Graphics g, Rectangle column)
{
g.setColor(Color.green.darker());
g.fillRect(column.x, column.y, column.width, column.height);
g.fillRect(column.x-20, column.y+column.height-10, column.width+40, 10);
g.fillRect(column.x-20, column.y-10, column.width+40, 10);
}
public void repaint(Graphics g)
{
g.setColor(new Color(153,204,255));
g.fillRect(0, 0, WIDTH, HEIGHT);
g.setColor(new Color(255,255,255));
g.fillOval(50, 50, 100, 100);
g.setColor(Color.YELLOW);
g.fillOval(600, 50, 100, 100);
g.setColor(new Color(156,93,82));
g.fillRect(0, HEIGHT - 120, WIDTH, 120);
g.setColor(new Color(128,255,0));
g.fillRect(0, HEIGHT - 120, WIDTH, 20);
g.setColor(Color.YELLOW);
g.fillRect(bee.x, bee.y, bee.width, bee.height);
for (Rectangle column : rect_column)
{
paintColumn(g, column);
}
g.setColor(Color.white);
g.setFont(new Font("Times New Roman", 1, 100));
if (!started)
{
g.drawString("Push A to start", 100, HEIGHT / 2 - 50);
}
if (gameOver)
{
g.drawString("Game Over", 100, HEIGHT / 2 - 50);
g.drawString("A to replay", 100, HEIGHT / 2 + 90);
}
}
public static void main(String[] args)
{
finalFlappy = new FinalFlappy();
}
#Override
public void mouseClicked(MouseEvent e)
{
jump();
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_A)
{
jump();
}
}
#Override
public void mousePressed(MouseEvent e)
{
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseEntered(MouseEvent e)
{
}
#Override
public void mouseExited(MouseEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
}
import java.awt.Graphics;
import javax.swing.JPanel;
public class FinalFlappyRend extends JPanel
{
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
FinalFlappy.finalFlappy.repaint(g);
}
}
I am working on making a Flappy bird game and I am stuck on how to make and display a timer that updates every second onto the screen
How do I make it start as the game starts and end as the game over pops up?
There are a few ways you might achieve what you're asking. The important thing to remember is, any solution is going to have a degree of drift, meaning that it's unlikely to absolutely accurate, the degree of drift will depend on a lot of factors, so just beware.
You could use a Swing Timer
It's among the safest means for updating the UI on a regular basis, it's also useful if your main loop is already based on a Swing Timer
See How to Use Swing Timers for more details
You could...
Maintain some kind of counter within in your main loop. This assumes that you're using a separate thread (although you can do the same thing with a Swing Timer) and are simply looping at some consistent rate
long tick = System.nanoTime();
long lastUpdate = -1;
while (true) {
long diff = System.nanoTime() - tick;
long seconds = TimeUnit.SECONDS.convert(diff, TimeUnit.NANOSECONDS);
if (seconds != lastUpdate) {
lastUpdate = seconds;
updateTimerLabel(seconds);
}
Thread.sleep(100);
}
This basically runs a while-loop, which calculates the difference between a given point in time (tick) and now, if it's a "second" difference, it then updates the UI (rather than constantly updating the UI with the same value)
The updateTimerLabel method basically updates the label with the specified time, but does so in a manner which is thread safe
protected void updateTimerLabel(long seconds) {
if (EventQueue.isDispatchThread()) {
timerLabel.setText(Long.toString(seconds));
} else {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
updateTimerLabel(seconds);
}
});
}
}
To make and display a timer that updates every second, Put this code in your main class:
private Timer timer = new Timer();
private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);
timer.schedule(new UpdateUITask(), 0, 1000);
private class UpdateUITask extends TimerTask {
int nSeconds = 0;
#Override
public void run() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
timeLabel.setText(String.valueOf(nSeconds++));
}
});
}
}

Why are my custom buttons not working?

So I've made custom buttons (yes, there is a reason I'm not using JButtons) and for some reason they're not working. I believe it's to do with the MouseAdapter I'm using, but I can't say for certain. To clarify, I've created the visual aspect of the buttons, and that works, but for some reason the clicking doesn't. I've put in debug code, as you can see, but it's not printing that either. Here's my code:
JPanel:
package com.kraken.towerdefense.graphics;
import com.kraken.towerdefense.TowerDefense;
import com.kraken.towerdefense.scene.Scene;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
public class Screen extends JPanel implements Runnable {
Thread thread = new Thread(this);
private int FPS = 0;
public Scene scene;
TowerDefense tD;
private boolean running = false;
public RoundRectangle2D.Float playGame, quitGame;
public boolean playGameHighlighted, quitGameHighlighted;
#Override
public void run() {
long lastFrame = System.currentTimeMillis();
int frames = 0;
running = true;
while (running) {
repaint();
frames++;
if (System.currentTimeMillis() - 1000 >= lastFrame) {
FPS = frames;
frames = 0;
lastFrame = System.currentTimeMillis();
}
}
System.exit(0);
}
public Screen(TowerDefense tD) {
thread.start();
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
playGameHighlighted = playGame.contains(e.getPoint());
quitGameHighlighted = quitGame.contains(e.getPoint());
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
if (playGameHighlighted) {
scene = Scene.GAME;
repaint();
System.out.println("playGameHighlighted and mouse clicked");
}
if (quitGameHighlighted) {
running = false;
System.out.println("quitGameHighlighted and mouse clicked");
}
System.out.println("mouse clicked");
}
});
this.tD = tD;
scene = Scene.MENU;
setBackground(new Color(217, 217, 217));
}
#Override
public void paintComponent(Graphics g2) {
super.paintComponent(g2);
playGame = new RoundRectangle2D.Float((getWidth() / 2) - 200, (getHeight() / 2) - 100, 400, 100, 10, 10);
quitGame = new RoundRectangle2D.Float((getWidth() / 2) - 200, (getHeight() / 2) + 20, 400, 100, 10, 10);
Graphics2D g = (Graphics2D) g2.create();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.clearRect(0, 0, getWidth(), getHeight());
g.drawString("FPS: " + FPS, 10, 10);
if (scene == Scene.MENU) {
if (playGameHighlighted) {
g.setColor(new Color(255, 152, 56));
} else {
g.setColor(new Color(4, 47, 61));
}
g.fill(playGame);
if (quitGameHighlighted) {
g.setColor(new Color(255, 152, 56));
} else {
g.setColor(new Color(4, 47, 61));
}
g.fill(quitGame);
g.setColor(Color.WHITE);
g.setFont(new Font("Gisha", Font.PLAIN, 20));
g.drawString("Play", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Play") / 2), (getHeight() / 2) - 45);
g.drawString("Quit", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Quit") / 2), (getHeight() / 2) + 75);
g.setColor(Color.BLACK);
g.setFont(new Font("Gisha", Font.PLAIN, 30));
g.drawString("Tower Defense Menu", (getWidth() / 2) - (g.getFontMetrics().stringWidth("Tower Defense Menu") / 2), (getHeight() / 4) - 15);
g.draw(playGame);
g.draw(quitGame);
}
}
}
JFrame:
package com.kraken.towerdefense;
import com.kraken.towerdefense.graphics.Screen;
import javax.swing.*;
public class TowerDefense extends JFrame {
public static void main(String[] args) {
new TowerDefense();
}
public TowerDefense() {
setExtendedState(MAXIMIZED_BOTH);
setUndecorated(true);
setTitle("Tower Defense");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
Screen screen = new Screen(this);
this.add(screen);
setVisible(true);
}
}
Scene Enum:
package com.kraken.towerdefense.scene;
public enum Scene {
MENU,
GAME
}
So that's my code, any help would be greatly appreciated. Thanks!
MouseMotionListener will only monitor a certain set of mouse events, in order to be notified about mouse click events, you need to use a MouseListener.
Luckily for you, it's really easy to use the MouseAdapter for both...
MouseAdapter ma = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
playGameHighlighted = playGame.contains(e.getPoint());
quitGameHighlighted = quitGame.contains(e.getPoint());
repaint();
}
#Override
public void mousePressed(MouseEvent e) {
if (playGameHighlighted) {
scene = Scene.GAME;
repaint();
System.out.println("playGameHighlighted and mouse clicked");
}
if (quitGameHighlighted) {
running = false;
System.out.println("quitGameHighlighted and mouse clicked");
}
System.out.println("mouse clicked");
}
};
addMouseMotionListener(ma);
addMouseListener(ma);
Take a closer look at How to Write a Mouse Listener for more details

Filling a HUD in Java

I've decided on making a HUD with the picture above, but I don't know what command in Java I need to use so as I can fill the top half and the bottom half separately.
I only know how to use the g.fillRect(); command, and it will take around twenty of these commands to fill said half.
public class HUD {
private Player player;
private BufferedImage image;
private Font font;
private Font font2;
private int Phealth = Player.getHealth();
public HUD(Player p) {
player = p;
try {
image = ImageIO.read(getClass().getResourceAsStream("/HUD/HUD_TEST.gif"));
font = new Font("Arial", Font.PLAIN, 10);
font2 = new Font("SANS_SERIF", Font.BOLD, 10);
}
catch(Exception e) {
e.printStackTrace();
}
}
public void draw(Graphics2D g) {
g.drawImage(image, 0, 10, null);
g.setFont(font2);
g.setColor(Color.black);
g.drawString("Health:", 30, 22);
g.drawString("Mana:", 25, 47);
g.setFont(font);
g.drawString(Player.getHealth() + "/" + player.getMaxHealth(), 64, 22);
g.drawString(player.getCubes() / 100 + "/" + player.getMaxCubes() / 100, 55, 47);
g.setColor(Color.red);
g.fillRect(1, 25, Phealth * 25, 4);
g.setColor(Color.blue);
g.fillRect(1, 31, player.getCubes() / 33, 4);
}
}
This is the code for the HUD so far.
Any help in filling the shape will help.
Removed Idea #1! (It didn't seem to work.)
Okay, Idea #2:
Image1
Image2
Image3
So, there are 3 .png images.
Draw Image1 first, followed by drawing Image2 and Image3 directly on top of it.
To fill up either the red/blue bars, clip Image2 and Image3 accordingly (i.e. cut away their left sides)
Take a look at this on clipping.
This will require some minor calculations on how much to clip, based on the HP/Mana of the Player, but it should be good enough.
This is what it should look like (Clipping and overlaying done in Paint)
UPDATE (Problem solved, using Idea #2!):
Code:
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
#SuppressWarnings("serial")
public class TestGraphics extends JFrame implements ActionListener
{
JPanel utilBar = new JPanel();
JButton hpUpBtn = new JButton("HP++");
JButton hpDownBtn = new JButton("HP--");
JButton mpUpBtn = new JButton("MP++");
JButton mpDownBtn = new JButton("MP--");
GraphicsPanel drawingArea = new GraphicsPanel();
TestGraphics()
{
setSize(600, 500);
setLayout(new BorderLayout());
add(utilBar, BorderLayout.NORTH);
utilBar.setLayout(new GridLayout(1, 4));
utilBar.add(hpUpBtn);
utilBar.add(hpDownBtn);
utilBar.add(mpUpBtn);
utilBar.add(mpDownBtn);
add(drawingArea, BorderLayout.CENTER);
hpUpBtn.addActionListener(this);
hpDownBtn.addActionListener(this);
mpUpBtn.addActionListener(this);
mpDownBtn.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == hpUpBtn) {
drawingArea.incHp();
}
else if (e.getSource() == hpDownBtn) {
drawingArea.decHp();
}
else if (e.getSource() == mpUpBtn) {
drawingArea.incMp();
}
else if (e.getSource() == mpDownBtn) {
drawingArea.decMp();
}
System.out.println("Player HP: " + drawingArea.getHp() +
" Player MP: " + drawingArea.getMp());
drawingArea.revalidate();
drawingArea.repaint();
}
public static void main(String[]agrs)
{
new TestGraphics();
}
}
#SuppressWarnings("serial")
class GraphicsPanel extends JPanel {
private static int baseX = 150;
private static int baseY = 150;
private static final int BAR_FULL = 287;
private static final int BAR_EMPTY = 8;
private BufferedImage image1 = null;
private BufferedImage image2 = null;
private BufferedImage image3 = null;
private int playerHp = 100;
private int playerMp = 100;
public GraphicsPanel() {
try {
// All 3 images are the same as those posted in answer
image1 = ImageIO.read(
getClass().getResourceAsStream("/Image1.png"));
image2 = ImageIO.read(
getClass().getResourceAsStream("/Image2.png"));
image3 = ImageIO.read(
getClass().getResourceAsStream("/Image3.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void incHp() { playerHp += (playerHp < 100) ? 5 : 0; }
public void decHp() { playerHp -= (playerHp > 0) ? 5 : 0; }
public void incMp() { playerMp += (playerMp < 100) ? 5 : 0; }
public void decMp() { playerMp -= (playerMp > 0) ? 5 : 0; }
public int getHp() { return playerHp; }
public int getMp() { return playerMp; }
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Clear the graphics
g.setClip(null);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 600, 600);
g.drawImage(image1, baseX, baseY, null);
int hpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerHp / 100.0));
g.setClip(baseX + BAR_EMPTY + hpPerc, 0, 600, 500);
g.drawImage(image2, baseX, baseY, null);
g.setClip(null);
int mpPerc = (int) ((BAR_FULL - BAR_EMPTY) * (playerMp / 100.0));
g.setClip(baseX + BAR_EMPTY + mpPerc, 0, 600, 500);
g.drawImage(image3, baseX, baseY + 78, null);
g.setClip(null);
}
}

Adding a Class extended with JPanel to an existing JPanel

I created a Class with JPanel extended to it. Then when I created an object of it and added to an existing JPanel, it doesn't show up. What am I doing wrong here?
public class StartTower extends JPanel{
private int value;
public StartTower(int value){
this.value = value;
}
public static StartTower send(int value){
return new StartTower(value);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(752, 359);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(120, 60, 10, 270);
g.fillRect(20, 330, 210, 10);
g.fillRect(375, 60, 10, 270);
g.fillRect(275, 330, 210, 10);
g.fillRect(630, 60, 10, 270);
g.fillRect(530, 330, 210, 10);
int val1 = 20;
int val2 = 315;
int val3 = 210;
int col = 100;
for (int i = 0; i < value; i++) {
g.setColor(new Color(100, col, 100));
g.fillRect(val1, val2, val3, 15);
System.out.println(val1 + " " + val2 + " " + val3 + " " + col);
val1 += 10;
val2 -= 15;
val3 -= 20;
col -= 10;
}
}
}
Class with JPanel extended
private void startBtActionPerformed(java.awt.event.ActionEvent evt) {
//mainPanel.repaint();
name = javax.swing.JOptionPane.showInputDialog(rootPane, "Enter you name!", "Ready?", WIDTH);
if (name != null) {
clockFunc(true);
game.initialDisk((int) disksSpinner.getValue());
StartTower startTower = new StartTower((int) disksSpinner.getValue());
mainPanel.setLayout(null);
this.add(startTower);
a2bBt.setEnabled(true);
a2cBt.setEnabled(true);
b2aBt.setEnabled(true);
b2cBt.setEnabled(true);
c2aBt.setEnabled(true);
c2bBt.setEnabled(true);
optimumLabel.setText(getNoOfOptimumMoves((int) disksSpinner.getValue()));
disksSpinner.setEnabled(false);
startBt.setEnabled(false);
}
}
Method where I made the object of the before said class and added it to the existing JPanel. (mainPanel is the existing JPanel created using drag drop in NetBeans).
Why isn't this showing up? What's wrong in the code? Thanks in advance!
I'm not sure what's your complete code, but I just tried this and it works fine:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class StartTower extends JPanel
{
private int value;
public StartTower(int value)
{
this.value = value;
}
public static StartTower send(int value)
{
return new StartTower(value);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(752, 359);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.fillRect(120, 60, 10, 270);
g.fillRect(20, 330, 210, 10);
g.fillRect(375, 60, 10, 270);
g.fillRect(275, 330, 210, 10);
g.fillRect(630, 60, 10, 270);
g.fillRect(530, 330, 210, 10);
int val1 = 20;
int val2 = 315;
int val3 = 210;
int col = 100;
for (int i = 0; i < value; i++)
{
g.setColor(new Color(100, col, 100));
g.fillRect(val1, val2, val3, 15);
System.out.println(val1 + " " + val2 + " " + val3 + " " + col);
val1 += 10;
val2 -= 15;
val3 -= 20;
col -= 10;
}
}
private static void createAndShowGUI()
{
StartTower startTower = new StartTower(5);
JFrame jFrame = new JFrame();
JPanel jPanel = new JPanel();
jPanel.add(startTower);
jFrame.getContentPane().add(jPanel);
jFrame.pack();
jFrame.setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If you are going to use null layout, which I don't recommend, then before you add a component you have to set its bounds so the null layout knows where to put it.
Doing without a layout

Cannot instantiate the type... ,what does it mean?

I've got this GUI that I want to run and when I try to make a Object out of the class I get the error Cannot instantiate the type GUI. So what does it mean and how can I fix?
The code in the mainclass
public static void main(String[] args){
//Classes
GUI go = new GUI();
//Running Class Methods
//JFrame
//JFrame frame = new JFrame("Yatsy");
go.setVisible(true);
go.setVisible(true);
//go.setLocation((dim.width - width) / 2, (dim.height - height) / 2);
go.setSize(width, height);
System.out.println(width + " " + height);
//draw paint = new draw();
//go.add(paint);
}
code inside the GUI class
public GUI(){
super();
panel = new JPanel();
roll = new JButton("Roll");
nextPlayer = new JButton("Next Player");
bDice1 = new JButton("dice");
quit = new JButton("Quit");
use = new JButton("Use");
roll.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(turn == true){
rollResult1 = roll1();
rollResult2 = roll2();
rollResult3 = roll3();
rollResult4 = roll4();
rollResult5 = roll5();
sRollResult1 = Integer.toString(rollResult1);
sRollResult2 = Integer.toString(rollResult2);
sRollResult3 = Integer.toString(rollResult3);
sRollResult4 = Integer.toString(rollResult4);
sRollResult5 = Integer.toString(rollResult5);
rolls++;
start = false;
repaint();
System.out.println( rollResult1 + " " + rollResult2 + " " + rollResult3 + " " + rollResult4 + " " + rollResult5);
//System.out.println( rollAI );
}
if(rolls == 3){
turn = false;
System.out.println("Out of rolls");
}
}
});
nextPlayer.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(rolls > 0){
rolls = 0;
System.out.println("Next player");
turn = true;
repaint();
start = true;
}
}
});
quit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(panel, BorderLayout.CENTER);
panel.setBackground(Color.BLUE);
add(quit, BorderLayout.SOUTH);
add(roll, BorderLayout.NORTH);
add(nextPlayer, BorderLayout.EAST);
Handlerclass handler = new Handlerclass();
panel.addMouseListener(handler);
}
So I wonder why do I get an error?
I'm using java 1.7!
For these who want to know this is the full code!!!!
package Christofer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public abstract class GUI extends JFrame implements MouseListener{
private static final long serialVersionUID = 1L;
int dice1, dice2, dice3, dice4, dice5;
private JButton roll;
private JButton nextPlayer;
private JButton bDice1;
private JButton quit;
private JButton use;
private JPanel panel;
public int rolls = 0;
public boolean turn = true;
public boolean start = true;
boolean saved1 = false, saved2 = false, saved3 = false, saved4 = false, saved5 = false;
int rollResult1;
int rollResult2;
int rollResult3;
int rollResult4;
int rollResult5;
String sRollResult1, sRollResult2, sRollResult3, sRollResult4, sRollResult5;
public GUI(){
super();
panel = new JPanel();
roll = new JButton("Roll");
nextPlayer = new JButton("Next Player");
bDice1 = new JButton("dice");
quit = new JButton("Quit");
use = new JButton("Use");
roll.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(turn == true){
rollResult1 = roll1();
rollResult2 = roll2();
rollResult3 = roll3();
rollResult4 = roll4();
rollResult5 = roll5();
sRollResult1 = Integer.toString(rollResult1);
sRollResult2 = Integer.toString(rollResult2);
sRollResult3 = Integer.toString(rollResult3);
sRollResult4 = Integer.toString(rollResult4);
sRollResult5 = Integer.toString(rollResult5);
rolls++;
start = false;
repaint();
System.out.println( rollResult1 + " " + rollResult2 + " " + rollResult3 + " " + rollResult4 + " " + rollResult5);
//System.out.println( rollAI );
}
if(rolls == 3){
turn = false;
System.out.println("Out of rolls");
}
}
});
nextPlayer.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
if(rolls > 0){
rolls = 0;
System.out.println("Next player");
turn = true;
repaint();
start = true;
}
}
});
quit.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
System.exit(0);
}
});
add(panel, BorderLayout.CENTER);
panel.setBackground(Color.BLUE);
add(quit, BorderLayout.SOUTH);
add(roll, BorderLayout.NORTH);
add(nextPlayer, BorderLayout.EAST);
Handlerclass handler = new Handlerclass();
panel.addMouseListener(handler);
}
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
this.setBackground(Color.BLUE);
g2d.setColor(Color.WHITE);
g2d.fillRoundRect(getWidth() / 2 - 75, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 1
g2d.fillRoundRect(getWidth() / 2 - 40, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 2
g2d.fillRoundRect(getWidth() / 2 - 5, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 3
g2d.fillRoundRect(getWidth() / 2 + 30, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 4
g2d.fillRoundRect(getWidth() / 2 + 65, getHeight() / 2 - 50, 30, 30, 5, 5); //Dice 5
//Score Board
g2d.fillRect(30, 70, 370, getHeight() - 125);
g2d.setColor(Color.BLACK);
g2d.drawLine(150, 70, 150, getHeight() - 30);
g2d.drawLine(30, 70, 400, 70);
g2d.drawString("Ones", 35, 85);
g2d.drawLine(30, 90, 400, 90);
g2d.drawString("Twos", 35, 105);
g2d.drawLine(30, 110, 400, 110);
g2d.drawString("Threes", 35, 125);
g2d.drawLine(30, 130, 400, 130);
g2d.drawString("Fours", 35, 145);
g2d.drawLine(30, 150, 400, 150);
g2d.drawString("Fives", 35, 165);
g2d.drawLine(30, 170, 400, 170);
g2d.drawString("Sixes", 35, 185);
g2d.drawLine(30, 190, 400, 190);
if(start == false){
g.setColor(Color.BLACK);
Font font = new Font("Arial", Font.PLAIN, 25);
g2d.setFont(font);
g2d.drawString( sRollResult1 + " " + sRollResult2 + " " + sRollResult3 + " " + sRollResult4 + " " + sRollResult5, getWidth() / 2 - 70 , getHeight() / 2 - 25 );
if(turn == false){
g2d.setColor(Color.RED);
g2d.drawString("Out Of Rolls", getWidth() / 2 - 70, getHeight() / 2 - 75);
}
}
}
public int roll1(){
if (saved1 == false){
dice1 = (int )(Math.random() * 6 + 1);
}
return dice1;
}
public int roll2(){
if (saved2 == false){
dice2 = (int )(Math.random() * 6 + 1);
}
return dice2;
}
public int roll3(){
if (saved3 == false){
dice3 = (int )(Math.random() * 6 + 1);
}
return dice3;
}
public int roll4(){
if (saved4 == false){
dice4 = (int )(Math.random() * 6 + 1);
}
return dice4;
}
public int roll5(){
if (saved5 == false){
dice5 = (int )(Math.random() * 6 + 1);
}
return dice5;
}
private class Handlerclass implements MouseListener{
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
mx = e.getX();
my = e.getY();
System.out.println("X: " + mx + " Y: " + my);
if(mx < getWidth() / 2 - 75 && mx > getWidth() / 2 - 45 && my < getHeight() / 2 - 50 && my > getHeight() / 2 - 20){
System.out.println("saved1 = true");
}
}
public void mouseReleased(MouseEvent e) {
}
}
}
I know that I've got some cleaning up to do
public abstract class GUI is your problem. You can't instantiate abstract classes.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You can create a subclass and instantiate that though.

Categories