Lately I've been attempting to replicate Space Invaders in java to help with learning about developing applications with java and the programming language in general. However I've run into a little problem with JFrame: the background color that I declared for the window doesn't stay, it just flashes and then reverts to the default. Here's my code:
import javax.imageio.ImageIO;`
import java.io.*;`
import javax.swing.*;`
import java.awt.*;`
import java.awt.image.*;`
import java.awt.image.ImageObserver;`
import java.awt.event.*;`
public class Invaders extends JPanel{
public static int x = 40;
public static int y = 345;
public static int h = 20;
public static int k = 180;
public static int move = 1;
static final Invaders m = new Invaders();
public static void main(String[] args){
final JFrame frame = new JFrame("Movement of 2d Shapes");
frame.setSize(404,390);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(m);
frame.setBackground(Color.BLACK);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Action actionRight = new AbstractAction(){
public void actionPerformed(ActionEvent actionRightEvent){
if(x <= 350){
x += 10;
m.repaint();
};
}
};
Action actionLeft = new AbstractAction(){
public void actionPerformed(ActionEvent actionLeftEvent){
if(x >= 10){
x -= 10;
m.repaint();
};
}
};
KeyStroke right = KeyStroke.getKeyStroke("RIGHT");
KeyStroke left = KeyStroke.getKeyStroke("LEFT");
InputMap inputMap = m.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
inputMap.put(right, "RIGHT");
inputMap.put(left, "LEFT");
m.getActionMap().put("RIGHT", actionRight);
m.getActionMap().put("LEFT", actionLeft);
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
draw(g);
cpu_move(m);
}
public void cpu_move(Invaders m){
if(h == 0){
move = 0;
}else if(h == 375){
move = 1;
}
if(move == 0){
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
h += 5;
m.repaint();
}else if(move == 1){
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
h -= 5;
m.repaint();
};
}
public void draw(Graphics g){
try{
g.drawImage(ImageIO.read(getClass().getResource(
"images/Ship.jpg")), x, y, 35, 23, Color.BLACK, null);
g.drawImage(ImageIO.read(getClass().getResource(
"images/Alien.jpg")), h, k, 28, 20, Color.BLACK, null);
}catch(IOException k){
Component temporaryLostComponent = null;
JOptionPane.showMessageDialog(temporaryLostComponent,
"one or more image files missing or corrupt");
}
}
}
What's wrong with the declaration of the background color? there are no errors when compiling, but it still does this. What am I doing wrong?
Try next :
frame.getContentPane().add(m);
m.setBackground(Color.BLACK);
instead of frame.setBackground(Color.BLACK); because Invaders m fills all frame.
Your backgound will be black with image.
frame.getContentPane().add(m);
//frame.setBackground(Color.BLACK);
frame.getContentPane().setBackground( Color.BLACK );
Read the section from the Swing tutorial on Using Top Level Containters to understand the structure of a frame. The content pane is painted on top of the frame.
Related
I'm trying to create a MS Paint-like software with Java Choice Menus, but I'm experiencing some difficulties with two functions in particular
I get a massive wall of error text upon selecting a colour from my Colour Menu. What I wish to achieve is selecting the colour converts the string containing the option into lower case, before setting the PenColour into that option
Drawing Lines don't seem to work, despite the same code being functional in a different applet that didn't use Choice. I want it to select two points which then have a line drawn between them.
Here is my Code
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.Choice;
public class PockettProjectTest1 extends Applet implements ActionListener, MouseListener, MouseMotionListener{
//Coordinates and sizes used to draw GUI
private final int GUI_HEIGHT = 100;
private final int GUI_START_X = 10;
private final int GUI_START_Y = 10;
private final int FIELD_SIZE = 11; //Numbers of characters for text field display
////////////////////////GLOBAL VARIABLES////////////////////////
private Dimension appletSize; //used to encapsulate the Applets dimensions
private int x, y, appletHeight, appletWidth, PenThick, PenMode, ShapeMode, ClickXO, ClickYO, ClickXN, ClickYN, ClickCount;
private String SizeString;
//a Panel is a container used here to hold and position the GUI components
private Panel guiPanel;
private Color PenColour;
//GUI components cv
public void init(){
//Disables the applet layout manager and stops automatic GUI component positioning
setLayout(null);
setBackground(Color.white);
addMouseListener(this);
addMouseMotionListener(this);
addMouseListener(this);
ClickCount = 0;
ClickXO = 0;
ClickYO = 0;
ClickXN = 0;
ClickYN = 0;
PenMode = 0;
ShapeMode = 0;
appletSize = this.getSize(); //captures the Applet dimensions
appletHeight = appletSize.height; //captures the Applet height
appletWidth = appletSize.width; //captures the Applet width
//Set up the Panel ready to hold the GUI components
guiPanel = new Panel();
guiPanel.setLocation(0, 0);
guiPanel.setSize(appletWidth,GUI_HEIGHT);
guiPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 40));
guiPanel.setBackground(Color.lightGray);
add(guiPanel);
Choice mode = new Choice();
Choice size = new Choice();
Choice color = new Choice();
Choice shape = new Choice();
mode.add("Pen");
mode.add("Eraser");
mode.add("Fill");
mode.add("Shape");
size.add("01px");
size.add("02px");
size.add("03px");
size.add("05px");
size.add("10px");
size.add("15px");
size.add("20px");
size.add("30px");
size.add("50px");
shape.add("N/A");
shape.add("Line");
shape.add("Oval");
shape.add("Oblong");
shape.add("Square");
shape.add("Circle");
shape.add("FillOval");
shape.add("FillOblong");
shape.add("FillSquare");
shape.add("FillCircle");
//add choice or combobox
guiPanel.add(mode);
guiPanel.add(size);
guiPanel.add(shape);
PenThick = 1;
PenColour = Color.black;
mode.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
PenMode = mode.getSelectedIndex();
}
});
size.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
SizeString = size.getSelectedItem();
PenThick = Integer.parseInt(SizeString.substring(0,2));
Graphics g = getGraphics();
}
});
//// Start of Issue 1:
colour.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
ColourString = colour.getSelectedItem();
ColourString.toLowerCase();
Color PenColour.getColor(ColourString);
}
});
/// End of Issue 1
shape.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie)
{
ShapeMode = shape.getSelectedIndex();
}
});
}
public void actionPerformed(ActionEvent e) {
}
////Issue 2:
public void mouseReleased(MouseEvent me){
if (PenMode == 3) {
if (ClickCount == 0) {
ClickXO = me.getX();
ClickYO = me.getY();
ClickCount ++;
System.out.println(ClickCount);
return;
}
if (ClickCount == 1) {
ClickXN = me.getX();
ClickYN = me.getY();
System.out.println(ClickCount);
Graphics g = getGraphics();
g.setColor(Color.black);
g.drawLine(ClickXO, ClickYO, ClickXN, ClickYN);
System.out.println(ClickXO);
System.out.println(ClickYO);
System.out.println(ClickXN);
System.out.println(ClickYN);
ClickCount = 0;
}
}
}
/// End of Issue 2
public void mousePressed(MouseEvent e){
}
public void mouseDragged(MouseEvent e){
if (PenMode == 0){
Graphics g = getGraphics();
g.setColor(Color.black);
g.fillOval(e.getX(), e.getY(), PenThick, PenThick);
}
if (PenMode == 1){
Graphics g = getGraphics();
g.setColor(Color.white);
g.fillRect(e.getX(), e.getY(), PenThick, PenThick);
}
}
public void mouseMoved(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
public void mouseClicked(MouseEvent e){
}
}
I have to have this code due by the end of Friday, so I hope I can get the issue solved by then.
I'm attempting to make Frogger in java for a school project but I'm having a lot of difficulties setting up KeyListener for the actual frog character.
I've tried setting up key bindings, requesting focus for the JPanel and JFrame, moving around where the character is initiated but nothing has seemed to work. This is the remnants of my attempts.
This is the program that runs my game.
import javax.swing.*;
public class Frogger
{
JFrame frame = new JFrame("Frogger");
CPT c = new CPT();
public Frogger()
{
frame.setBounds(0,0,700,500);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(c);
}
public static void main(String[] args){
new Frogger();
}
}
The main game
public CPT() {
setLayout(new BorderLayout());
label = new JLabel("Frogger");
frame1 = new JFrame("Main");
label.setFont(new Font("Serif", Font.BOLD,50));
label.setBounds(275,10,250,250);
button1 = new JButton("PLAY");
button1.setBounds(300,350,100,50);
button1.setOpaque(false);
button1.setVisible(true);
this.setOpaque(false);
this.setLayout(null);
this.add(label);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
frame1.setSize(700,500);
frame1.setResizable(false);
frame1.setFocusable(false);
button1.setVisible(false);
frame1.add(new TrainCanvas());
frame1.add(p1);
p1.requestFocus();
}
});
this.add(button1); }
This is the TrainCanvas class that Draws the cars in the games as well as the frog
class TrainCanvas extends JComponent
{
private int lastX = 0;
private int lastX_1 = 0;
private int lastX_2 = 0;
public TrainCanvas() {
Thread animationThread = new Thread(new Runnable() {
public void run() {
while (true) {
repaint();
try {Thread.sleep(10);} catch (Exception ex) {}
}
}
});
animationThread.start();
}
public void paintComponent(Graphics g) {
Graphics2D gg = (Graphics2D) g;
//Draws Train 1
int w = getWidth();
int h = getHeight();
int trainW_1 = 100;
int trainH_1 = 5;
int trainSpeed_1 = 3;
int x = lastX + trainSpeed_1;
if (x > w + trainW_1) {
x = -trainW_1;
}
gg.setColor(Color.BLACK);
gg.fillRect(x, h/2 + trainH_1, trainW_1, trainH_1);
lastX = x;
Graphics2D g3 = (Graphics2D) g;
frog = new Rectangle(f_x,f_y,25,25);
g3.fill(frog);
g3.setColor(Color.GREEN);
}
}
Finally, the Key Listener
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()== KeyEvent.VK_UP)
{
CPT.f_y -= 100;
repaint();
}
else if(e.getKeyCode()== KeyEvent.VK_RIGHT)
{
CPT.f_x += 100;
repaint();
}
else if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
CPT.f_x -= 100;
repaint();
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
CPT.f_y += 100;
repaint();
}
else {}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
}
The program runs perfectly fine without giving me any errors, which is making this troublesome. Whenever it gets to the main game window, none of the keys seem to work.
I'm trying to implement a KeyListener in a Space Invaders game in Java to move the ship (by now, it's just a red rectangle).
I think it's fine implemented, but i can't make it works.
Here is the ship's one:
import java.awt.Color;
import java.awt.Graphics;
public class Nave{
int x, y;
int AnchoNave = 40, AltoNave = 40; // WIDTH_SHIP and HIGH_SHIP
Finestra f; // WINDOW
int velocidad = 4, v = 0; // VELOCITY
Joc j;
Nave(Finestra f, int x, int y){
this.f = f;
this.x = x;
this.y = y;
}
void pintaNave(Graphics g){
g.setColor(Color.RED);
g.drawRect(x, y, AnchoNave, AltoNave);
g.setColor(Color.RED);
g.fillRect(x, y, AnchoNave, AltoNave);
}
void movimiento(){ // this is not in the loop now.
x+=velocidad;
if (x>f.AMPLE-AnchoNave-10){
x=0;
}
}
}
Here is the Window's one:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;
import javax.swing.JFrame;
public class Finestra extends JFrame implements ActionListener, KeyListener{
Image im;
Graphics g;
int AMPLE=600,ALT=500; // WIDTH and HIGH
Joc j;
Nave nave; // Nave = SHIP
int velocidad = 10; // VELOCITY
public static void main(String[] args) {
new Finestra(); // Finestra = WINDOW
}
Finestra(){
super("-+- Space Invaders -+-");
setVisible(true);
setSize(AMPLE,ALT);
im=this.createImage(AMPLE, ALT);
g=im.getGraphics();
j=new Joc(this);
j.playing();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.drawImage(im, 0,0, null);
}
#Override
public void actionPerformed(ActionEvent e) {
j.nave.x =j.nave.x + j.nave.v;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int tecla = e.getKeyCode();
if (tecla == KeyEvent.VK_RIGHT)
j.nave.v = +10;
if (tecla == KeyEvent.VK_LEFT)
j.nave.v = -10;
}
#Override
public void keyReleased(KeyEvent e) {
j.nave.v = 0;
}
#Override
public void keyTyped(KeyEvent e) {}
}
And finally this is the class that contains the loop of the game:
import java.awt.Color;
import java.awt.Graphics;
public class Joc{
Finestra f; // WINDOW
Enemigos c1[]; // ENEMIES
Nave nave; // SHIP
Joc(Finestra f){ // JOC = GAME
this.f=f;
}
void playing() {
initicalitzaJoc();
do {
moviments(); // MOVEMENTS
detectaColisions(); // COLLISION DETECTION
pintarPantalla(f.g); // PAINT SCREEN
f.repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}while(true);
}
private void detectaColisions() {
}
private void moviments() {
for(int i=0;i<c1.length;i++)
c1[i].movimiento();
}
private void initicalitzaJoc() {
c1 = new Enemigos[15]; // ENEMIES
for (int i=0; i<5; i++)
c1[i] = new Enemigos(f, 100+i*80, 100, 5);
for (int i=5; i<10; i++)
c1[i] = new Enemigos(f, 100+(i-5)*80, 150, 5);
for (int i=10; i<15; i++)
c1[i] = new Enemigos(f, 100+(i-10)*80, 200, 5);
// Nave del jugador: // PLAYER'S SHIP
nave = new Nave(f,300-40/2, 500-40-5);
}
void pintarPantalla(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, 600,500);
for (int i=0; i<5; i++)
c1[i].pinta(g,1);;
for (int i=5; i<10; i++)
c1[i].pinta(g,3);
for (int i=10; i<15; i++)
c1[i].pinta(g,6);
nave.pintaNave(g);
}
}
I don't know where the mistake could be, maybe in the loop... i don't know.
The question is how can i fixed it to can move the ship using the keyboard?
This Space Invaders is a homework, I'm obliged to use the KeyListener... How can I make it works ?
I'have found the answer.
The problem was that the class "Finestra" ejecute the function "playing" (so the loop starts) before reading the keys.
It's enough chasing the order:
Finestra(){
super("-+- Space Invaders -+-");
setVisible(true);
setSize(AMPLE,ALT);
im=this.createImage(AMPLE, ALT);
g=im.getGraphics();
j=new Joc(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
System.out.println("hola");
j.playing(); // enter the loop after reading the keys.
}
Looking at your key event handler:
#Override
public void keyPressed(KeyEvent e) {
int tecla = e.getKeyCode();
if (tecla == KeyEvent.VK_RIGHT)
j.nave.v = +10;
if (tecla == KeyEvent.VK_LEFT)
j.nave.v = -10;
}
It changes a variable called 'v' on your ship (nave).
Then your movimiento (presumably 'move') method on your ship uses another variable, velocidad. It completely ignores v!
Delete the variable v and just use velocidad.
Also, you only ever call movimiento on your enemy ships, never on your player's ship! So naturally, it never moves.
I have been following the Java Game Programming for Beginners tutorial series, and wished to experiment by applying a background image. Unfortunately, when I render it through the paintComponent method, it moves with my sprite (albeit at one unit continuously as opposed to five); and when I render it through the paint method, I get a strange, flickering box that matches the color designated in the setBackground (color) property of the JFrame and it moves with the sprite identically to that of the prior instance (within paintComponent).
How might I code the image so as to remain static, as a background should be?
Code:
public class JavaGame extends JFrame{
int x, y;
private Image dbImage;
private Graphics dbg;
Image ghost;
Image bg;
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if(keyCode == e.VK_LEFT){
if(x <= 8)
x = 8;
else
x += -5;
}
if(keyCode == e.VK_RIGHT){
if(x >= 235)
x = 235;
else
x += +5;
}
if(keyCode == e.VK_UP){
if(y <= 18)
y = 18;
else
y += -5;
}
if(keyCode == e.VK_DOWN){
if(y >= 235)
y = 235;
else
y += +5;
}
}
public void keyReleased(KeyEvent e){
}
}
public JavaGame(){
//Load images
ImageIcon i = new ImageIcon("C:/Users/Taylor/workspace/Java game/src/ghost.png");
ghost = i.getImage();
ImageIcon j = new ImageIcon("C:/Users/Taylor/workspace/Java game/src/bg.png");
bg = j.getImage();
//Game properties
addKeyListener(new AL());
setTitle("Java Game");
setSize(500, 500);
setResizable(false);
setVisible(true);
setBackground(Color.GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
public void paint(Graphics g){
g.drawImage(bg, 0, 0, null);
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, x, y, this);
}
public void paintComponent(Graphics g){
g.setColor(Color.WHITE);
g.drawImage(ghost, x, y, this);
repaint();
}
public static void main(String[] args) {
new JavaGame();
}
Pictures:
Were you copy/pasting code at random? That is what it looked like. There were so many odd aspects to that code that I did not document them all (a good one for code review, maybe). The example uses an asynchronous method to load the images (in order to get the animated image, animating). Use ImageIO.read(URL) for a synchronous way to load static images.
Here are some brief tips:
By the time this becomes deployed, the images will likely become an embedded resource and will not be accessible by File object. Add them to the run-time class-path and access them by URL.
Swing GUIs should be started and altered on the EDT (see the change to the main()).
Always call super.paint(g); (or paintComponent(g)) at the start of the method.
Don't extend frame, don't paint to a top level component. Instead extend panel and override paintComponent(). Add the panel to the frame.
Code
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class JavaGame extends JPanel {
int x, y;
private Image dbImage;
private Graphics dbg;
Image ghost;
Image bg;
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
if (x <= 8)
x = 8;
else
x += -5;
}
if (keyCode == e.VK_RIGHT) {
if (x >= 235)
x = 235;
else
x += +5;
}
if (keyCode == e.VK_UP) {
if (y <= 18)
y = 18;
else
y += -5;
}
if (keyCode == e.VK_DOWN) {
if (y >= 235)
y = 235;
else
y += +5;
}
}
public void keyReleased(KeyEvent e) {
}
}
public JavaGame() throws Exception {
// Load images
//ImageIcon i = new ImageIcon(
// "C:/Users/Taylor/workspace/Java game/src/ghost.png");
URL urlGhost = new URL("http://1point1c.org/gif/thum/plnttm.gif");
ghost = Toolkit.getDefaultToolkit().createImage(urlGhost);
//ImageIcon j = new ImageIcon(
// "C:/Users/Taylor/workspace/Java game/src/bg.png");
URL urlBG = new URL("http://pscode.org/media/stromlo2.jpg");
bg = Toolkit.getDefaultToolkit().createImage(urlBG);
setFocusable(true);
// Game properties
addKeyListener(new AL());
x = 150;
y = 150;
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
repaint();
}
};
Timer timer = new Timer(50,al);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bg, 0, 0, null);
//dbImage = createImage(getWidth(), getHeight());
//dbg = dbImage.getGraphics();
//paintComponent(dbg);
g.drawImage(dbImage, x, y, this);
g.setColor(Color.WHITE);
g.drawImage(ghost, x, y, this);
//repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFrame f = new JFrame("Java Game");
f.setSize(500, 500);
f.setResizable(false);
f.setVisible(true);
f.setBackground(Color.GRAY);
f.setContentPane(new JavaGame());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I have displayed an image(ball) inside the JApplet, now I want the image to move in a vertical way (up and down). The problem is I don't know how to do it.
Could someone has an idea about this matter?
You need to set the position of that image to some calculated value (means you caculate the vertical position using time, speed and maybe other restrictions).
How you'd set that position depends on how you draw the image.
Example, based on drawing in the applet's (or a nested component's) paint(Graphics g) method:
//first calculate the y-position
int yPos += timeSinceLastPaint * speed; //increment the position
if( (speed > 0 && yPos > someMaxY) || (speed < 0 && yPos <0 ) ) {
speed *= -1; //if the position has reached the bottom (max y) or the top invert the direction
}
//in your paint(Graphics g) method:
g.drawImage(image, yPos, x, null);
Then you'd have to constantly repaint the applet.
More information on animations in applets can be found here: http://download.oracle.com/javase/tutorial/uiswing/components/applet.html
another example for javax.swing.Timer with moving Ojbects created by paintComponent(Graphics g), and I have lots of Start, not some blurred Mikado :-)
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class AnimationBackground {
private Random random = new Random();
private JFrame frame = new JFrame("Animation Background");
private final MyJPanel panel = new MyJPanel();
private JLabel label = new JLabel("This is a Starry background.", JLabel.CENTER);
private JPanel stopPanel = new JPanel();
private JPanel startPanel = new JPanel();
public AnimationBackground() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel.setBackground(Color.BLACK);
for (int i = 0; i < 50; i++) {
Star star = new Star(new Point(random.nextInt(490), random.nextInt(490)));
star.setColor(new Color(100 + random.nextInt(155), 100 + random.nextInt(155), 100 + random.nextInt(155)));
star.setxIncr(-3 + random.nextInt(7));
star.setyIncr(-3 + random.nextInt(7));
panel.add(star);
}
panel.setLayout(new GridLayout(10, 1));
label.setForeground(Color.WHITE);
panel.add(label);
stopPanel.setOpaque(false);
stopPanel.add(new JButton(new AbstractAction("Stop this madness!!") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
panel.stopAnimation();
}
}));
panel.add(stopPanel);
startPanel.setOpaque(false);
startPanel.add(new JButton(new AbstractAction("Start moving...") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
panel.startAnimation();
}
}));
panel.add(startPanel);
frame.add(panel);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
AnimationBackground aBg = new AnimationBackground();
}
});
}
private class Star extends Polygon {
private static final long serialVersionUID = 1L;
private Point location = null;
private Color color = Color.YELLOW;
private int xIncr, yIncr;
static final int WIDTH = 500, HEIGHT = 500;
Star(Point location) {
int x = location.x;
int y = location.y;
this.location = location;
this.addPoint(x, y + 8);
this.addPoint(x + 8, y + 8);
this.addPoint(x + 11, y);
this.addPoint(x + 14, y + 8);
this.addPoint(x + 22, y + 8);
this.addPoint(x + 17, y + 12);
this.addPoint(x + 21, y + 20);
this.addPoint(x + 11, y + 14);
this.addPoint(x + 3, y + 20);
this.addPoint(x + 6, y + 12);
}
public void setColor(Color color) {
this.color = color;
}
public void move() {
if (location.x < 0 || location.x > WIDTH) {
xIncr = -xIncr;
}
if (location.y < 0 || location.y > WIDTH) {
yIncr = -yIncr;
}
translate(xIncr, yIncr);
location.setLocation(location.x + xIncr, location.y + yIncr);
}
public void setxIncr(int xIncr) {
this.xIncr = xIncr;
}
public void setyIncr(int yIncr) {
this.yIncr = yIncr;
}
public Color getColor() {
return color;
}
}
private class MyJPanel extends JPanel {
private static final long serialVersionUID = 1L;
private ArrayList<Star> stars = new ArrayList<Star>();
private Timer timer = new Timer(20, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Star star : stars) {
star.move();
}
repaint();
}
});
public void stopAnimation() {
if (timer.isRunning()) {
timer.stop();
}
}
public void startAnimation() {
if (!timer.isRunning()) {
timer.start();
}
}
#Override
public void addNotify() {
super.addNotify();
timer.start();
}
#Override
public void removeNotify() {
super.removeNotify();
timer.stop();
}
MyJPanel() {
this.setPreferredSize(new Dimension(512, 512));
}
public void add(Star star) {
stars.add(star);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (Star star : stars) {
g.setColor(star.getColor());
g.fillPolygon(star);
}
}
}
}
How to move the image inside the JApplet ..?
Pretty much exactly the same way you might do it in a JFrame, JComponent or JPanel or...
Or to put that another way, nothing to do with applets and everything to do with Graphics2D. For more details, see the 2D Graphics Trail of the Java Tutorial.
When you've figured how to move an image and paint it to a Graphics2D, implement that logic in a JComponent or JPanel's paintComponent(Graphics) method and drop the component with moving image into a JApplet or JFrame (or a JPanel etc.).
For the animation side of it, use a javax.swing.Timer as seen in this example. This example does not extend any component. Instead, it creates a BufferedImage and adds it to a JLabel that is displayed to the user. When the timer fires, the code grabs the Graphics object of the image, and proceeds from there to draw the bouncing lines.
import java.awt.image.BufferedImage;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.*;
import javax.swing.*;
import java.util.Random;
class LineAnimator {
public static void main(String[] args) {
final int w = 640;
final int h = 480;
final RenderingHints hints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON
);
hints.put(
RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY
);
final BufferedImage bi = new BufferedImage(w,h, BufferedImage.TYPE_INT_ARGB);
final JLabel l = new JLabel(new ImageIcon(bi));
final BouncingLine[] lines = new BouncingLine[100];
int factor = 1;
for (int ii=0; ii<lines.length; ii++) {
lines[ii] = new BouncingLine(w*factor,h*factor);
}
final Font font = new Font("Arial", Font.BOLD, 30);
ActionListener al = new ActionListener() {
int count = 0;
long lastTime;
String fps = "";
private final BasicStroke stroke = new BasicStroke(6);
public void actionPerformed(ActionEvent ae) {
count++;
Graphics2D g = bi.createGraphics();
g.setRenderingHints(hints);
g.setColor(new Color(55,12,59));
g.fillRect(0,0,w,h);
g.setStroke(stroke);
for (int ii=0; ii<lines.length; ii++) {
lines[ii].move();
lines[ii].paint(g);
}
if ( System.currentTimeMillis()-lastTime>1000 ) {
lastTime = System.currentTimeMillis();
fps = count + " FPS";
count = 0;
}
g.setColor(Color.YELLOW);
g.setFont(font);
g.drawString(fps,5,h-5);
l.repaint();
g.dispose();
}
};
Timer timer = new Timer(25,al);
timer.start();
JOptionPane.showMessageDialog(null, l);
//System.exit(0);
timer.stop();
}
}
class BouncingLine {
private final Color color;
private static final Random random = new Random();
Line2D line;
int w;
int h;
int x1;
int y1;
int x2;
int y2;
BouncingLine(int w, int h) {
line = new Line2D.Double(random.nextInt(w),random.nextInt(h),random.nextInt(w),random.nextInt(h));
this.w = w;
this.h = h;
this.color = new Color(
random.nextInt(255)
,random.nextInt(255)
,random.nextInt(255)
,64+random.nextInt(128)
);
x1 = (random.nextBoolean() ? 1 : -1);
y1 = (random.nextBoolean() ? 1 : -1);
x2 = -x1;
y2 = -y1;
}
public void move() {
int tx1 = 0;
if (line.getX1()+x1>0 && line.getX1()+x1<w) {
tx1 = (int)line.getX1()+x1;
} else {
x1 = -x1;
tx1 = (int)line.getX1()+x1;
}
int ty1 = 0;
if (line.getY1()+y1>0 && line.getY1()+y1<h) {
ty1 = (int)line.getY1()+y1;
} else {
y1 = -y1;
ty1 = (int)line.getY1()+y1;
}
int tx2 = 0;
if (line.getX2()+x2>0 && line.getX2()+x2<w) {
tx2 = (int)line.getX2()+x2;
} else {
x2 = -x2;
tx2 = (int)line.getX2()+x2;
}
int ty2 = 0;
if (line.getY2()+y2>0 && line.getY2()+y2<h) {
ty2 = (int)line.getY2()+y2;
} else {
y2 = -y2;
ty2 = (int)line.getY2()+y2;
}
line.setLine(tx1,ty1,tx2,ty2);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setColor(color);
//line.set
g2.draw(line);
}
}
Update 1
I want to do it in JApplet(1) using the image(2), is it possible(3)?
The examples by mKorbel and myself feature either an image in a JLabel or custom rendering in a JPanel. In our case, we added the components to a JOptionPane & a JFrame. Either example could be just as easily added to a JApplet, or a JDialog, or as part of another panel, or.. See the Laying Out Components Within a Container lesson & Using Top-Level Containers in the Java Tutorial for more details.
Instead of the stars or lines in our examples, ..paint your image. My example goes so far as to demonstrate how to get the position to bounce around within the bounds of the container.
Sure it is possible, but "Batteries not included". Our intention is to give you some ideas that you can then adapt to your bouncing ball applet. I doubt anyone is going to create an example for you, using balls, in an applet. Though if you post an SSCCE that shows your intent and what you tried, I (and others) would often run with that source. If you want more specific answers, ask a more specific SSCCE. ;)
I want to do it in JApplet.
Why not both? You can have a hybrid application/applet as shown in this animation.