how do i convert from private inner class to a runnable interface? - java

so im given a working code as below, but then i have to convert it to use runnable interface
package lab12;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MultiThreaded2 extends JFrame implements ActionListener {
public static final int WIDTH = 600;
public static final int HEIGHT = 400;
public static final int FILL_WIDTH = 600;
public static final int FILL_HEIGHT = 400;
public static final int SQUARE_SIZE = 10;
public static final int PAUSE = 100; // milliseconds
private JPanel box;
public static void main(String[] args) {
MultiThreaded2 gui = new MultiThreaded2();
gui.setVisible(true);
}
public MultiThreaded2() {
setSize(WIDTH, HEIGHT);
setTitle("Threaded Fill Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
box = new JPanel();
add(box, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
JButton startButton = new JButton("Start");
startButton.addActionListener(this);
buttonPanel.add(startButton);
JButton stopButton = new JButton("Stop");
stopButton.addActionListener(this);
buttonPanel.add(stopButton);
add(buttonPanel, BorderLayout.SOUTH);
}
public void run() {
Graphics g = box.getGraphics();
int count = 0;
for (int y = 0; y < FILL_HEIGHT; y = y + SQUARE_SIZE) {
for (int x = 0; x < FILL_WIDTH; x = x + SQUARE_SIZE) {
if (count % 2 == 0) {
g.setColor(Color.red);
g.fillRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
} else {
g.setColor(Color.blue);
g.drawRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
}
try {
Thread.sleep(PAUSE);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
}
}
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Start")) {
SecondThread secondThread = new SecondThread();
secondThread.start();
} else if (e.getActionCommand().equals("Stop")) {
System.exit(0);
}
}
private class SecondThread extends Thread {
public void run() {
Graphics g = box.getGraphics();
int count = 0;
for (int y = 0; y < FILL_HEIGHT; y = y + SQUARE_SIZE) {
for (int x = 0; x < FILL_WIDTH; x = x + SQUARE_SIZE) {
if (count % 2 == 0) {
g.setColor(Color.red);
g.fillRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
} else {
g.setColor(Color.blue);
g.drawRect(x, y, SQUARE_SIZE, SQUARE_SIZE);
}
try {
Thread.sleep(PAUSE);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
count++;
}
}
}
}
}
i understand that i must do something tot he public class secondthread yeah? but i dont know how to convert it to runnable since everything is working already.
i tried deleting the "extends thread" and insert " implements runnable" but that just gives me error. adding both "extends thread" and "implements runnable" works but i doubt thats what i had to do

It's kind of hard for anybody to tell you what an error message means if you don't tell us what the error message said, but here's a guess:
If you do nothing else but change SecondThread extends Thread to SecondThread implements Runnable, then secondThread.start() isn't going to compile because your SecondThread class does not define a start() method.
So, given a ... implements Runnable object, how do you get a thread to run it?
I suggest you spend some time with the Java Concurrency tutorial. https://docs.oracle.com/javase/tutorial/essential/concurrency/
The answer to my question is right near the beginning.

Related

How to clear in jframe

I have a situation where I'm moving a ball. However, after struggling with the queue that repaint() places paintComponent(Graphics g) in. I resorted to using paintImmediately. The problem now is that without access to super.paintComponent(g), I don't know how to clear the canvas each time before I paint. So one possible answer to my question would be a way to clear the canvas by itself. I also found that Threads could be a possible solution but after a great many attempts to implement that idea, I still don't understand that so if someone could show correct implementation for that I would be very grateful.
Here is my code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
public class PhysicsEngine extends JPanel {
double x, y;
JPanel pan;
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;
public static void main(String[] args) {
JFrame frame = new JFrame("Ball Engine");
PhysicsEngine gui = new PhysicsEngine();
frame.add(gui, BorderLayout.CENTER);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public PhysicsEngine() {
b1 = new JButton("1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
startFirst();
} catch (InterruptedException exception) {
}
}
});
this.add(b1);
b2 = new JButton("2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startSecond();
} catch (InterruptedException exception) {
}
}
});
this.add(b2);
b3 = new JButton("3");
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startThird();
} catch (InterruptedException exception) {
}
}
});
this.add(b3);
b4 = new JButton("4");
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startFourth();
} catch (InterruptedException exception) {
}
}
});
this.add(b4);
b5 = new JButton("5");
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startFifth();
} catch (InterruptedException exception) {
}
}
});
this.add(b5);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("" + y);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval((int) x, (int) y, 30, 30);
}
public void startFirst() throws InterruptedException {
x = 300;
y = 80;
// xPos= 0*t*t + 0*t + 300 this is constant at 300
for(int t = 1; t<70;t++){
y = .1 * t * t + 0 * t + 80; // parametric equation for y
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startSecond() throws InterruptedException {
x = 300;
y = 550;
for (int t = 1;t<150; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
y = .1 * t * t - 15 * t + 550; // parametric equation for y
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startThird() throws InterruptedException {
y = 550;
x = 50;
for (int t = 1;t<150; t++) {
y = .1 * t * t - 15 * t + 550; // parametric equation for y
x = 0 * t * t + 3 * t + 50; // parametric equation for x
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startFourth() throws InterruptedException {
y = 50;
x = -4;
for (int t = 1;t<110; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
y = .001*t * t * t + 50; // given parametric equation for y
x = t - 4; // given parametric equation for x
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
public void startFifth() throws InterruptedException {
for (int t = 1; t < 130 /* goes for 1.5 seconds */; t++) {
y = 200 * Math.sin(.05*t) + 300; // given parametric equation for y
x = 200 * Math.cos(.05*t) + 300; // given parametric equation for x
repaint();
paintImmediately((int)x, (int)y, 30, 30);
Thread.sleep(10);
}
}
}
Your problem isn't the "paint queue", it's the fact that you're violating the single threaded nature of the API, by calling Thread.sleep within the context of the EDT.
Instead of using for-loops with Thread.sleep in them, you should make use of a Swing Timer which updates the state of the variables paintComponent relies on (and call repaint)
Swing Timer can be thought of a pseudo loop, whose ActionListener is called within the context of the EDT, making it safe to update the UI from
Start by having a look at Concurrency in Swing and How to Use Swing Timers for more details
As a conceptual example...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private PhysicsPane physicsPane;
public TestPane() {
physicsPane = new PhysicsPane();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = gbc.REMAINDER;
JButton b1 = new JButton("1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
startFirst();
}
});
this.add(b1, gbc);
this.add(physicsPane, gbc);
}
protected void startFirst() {
physicsPane.startFirst();
}
}
public class PhysicsPane extends JPanel {
private Timer timer;
private double xPos, yPos;
private int tick;
public PhysicsPane() {
setBackground(Color.BLUE);
}
protected void stopTimer() {
if (timer == null) {
return;
}
timer.stop();
timer = null;
}
public void startFirst() {
stopTimer();
xPos = 300;
yPos = 500;
tick = 0;
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (tick >= 150) {
stopTimer();
return;
}
yPos = .1 * tick * tick - 15 * tick + 550;
tick++;
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 600);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(Color.RED);
g2d.fillOval((int) xPos, (int) yPos, 30, 30);
g2d.dispose();
}
}
}

Overrided paint method not being called after repaint is

My problem is essentially creating a physics engine with a few different scenarios. I would like to consolidate the different scenarios into one window by having buttons that run each individually. The frame works properly and the buttons show up and can be pressed; however, that print line in the pain method is never happening and from there I concluded that paint is not being called even after repaint is. I understand that they are not the same but I don't understand why paint isn't being accessed in this instance compared to others.
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import javax.swing.JButton;
public class PhysicsEngine extends JPanel{
double x ,y;
JFrame frame;
JPanel pan;
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;
public static void main(String[] args){
PhysicsEngine gui = new PhysicsEngine();
}
public PhysicsEngine(){
frame = new JFrame("Ball Engine");
pan = new JPanel();
frame.add(pan);
b1 = new JButton("1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event){
try{
startFirst();
}
catch(InterruptedException exception){}
}
});
pan.add(b1);
b2 = new JButton("2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try{
startSecond();
}
catch(InterruptedException exception){}
}
});
pan.add(b2);
b3 = new JButton("3");
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try{
startThird();
}
catch(InterruptedException exception){}
}
});
pan.add(b3);
b4 = new JButton("4");
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try{
startFourth();
}
catch(InterruptedException exception){}
}
});
pan.add(b4);
b5 = new JButton("5");
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
try{
startFifth();
}
catch(InterruptedException exception){}
}
});
pan.add(b5);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
super.paint(g);
System.out.println(""+y);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval((int)x, (int)y, 30, 30);
}
public void startFirst() throws InterruptedException{
x = 300;
for(int t = 1;;t++){
//xPos= 0*t*t + 0*t + 300 this is constant at 300
if(y>=615) break; //stops the loop when the ball is off the screen
y = .1*t*t + 0*t + 80; //parametric equation for y
repaint();
Thread.sleep(10);
}
}
public void startSecond() throws InterruptedException{
x = 300;
for(int t = 1;;t++){
//xPos= 0*t*t + 0*t + 300 this is constant at 300
if(y>=615) break; //stops the loop when the ball is off the screen
y = .1*t*t - 10*t + 550; //parametric equation for y
repaint();
Thread.sleep(10);
}
}
public void startThird() throws InterruptedException{
for(int t = 1;;t++){
if(y>=615||x>=615) break; //stops the loop when the ball is off the screen
y = .1*t*t - 10*t + 550; //parametric equation for y
x = 0*t*t + 5*t + 50; //parametric equation for x
repaint();
Thread.sleep(10);
}
}
public void startFourth() throws InterruptedException{
for(int t = 1;;t++){
//xPos= 0*t*t + 0*t + 300 this is constant at 300
if(y>=615||x>=615) break; //stops the loop when the ball is off the screen
y = t*t*t + 50; //given parametric equation for y
x = t - 4; //given parametric equation for x
repaint();
Thread.sleep(10);
}
}
public void startFifth() throws InterruptedException{
for(int t = 1;t<500 /* goes for 5 seconds */;t++){
y = 200*Math.sin(t) + 300; //given parametric equation for y
x = 200*Math.cos(t) + 300; //given parametric equation for x
repaint();
Thread.sleep(10);
}
}
}
The basic problem is you are overriding the paint() method of the PhysicsEngine class. But you never add an instance of this class to the frame.
However, the bigger problem is the structure of your class. Your main class should not be extending a JPanel just so you can create a JFrame. The logic for creating the frame should be in the main() method and then your PysicsEngine panel should contain all the components you want to build for your frame. Also, custom painting should be done by overriding the paintComponent(...) method, not the paint() method.
Read the section from the Swing tutorial on Custom Painting for basic painting information and demos.
Then you can look at other sections in the tutorial for a better way to structure your code. For example the ButtonDemo code found in the How to Use Buttons tutorial will show you how to extend a JPanel and add buttons to it.
repaint() stores a request for refreshing a component, request that will be executed by the GUI thread later on. But a component will be refreshed only if it is visible on screen, alas your PhysicsEngine class doesn't seem to be used as a visible component in some visible GUI hierarchy.
Your paint method should be paintComponent and also should call the paintComponent method of super class.
And you don't add the PhysicsEngine JPanel into the JFrame, and it is very bad approach to create a JFrame in the constructor of JPanel subclass. I create a JFrame in the main method and create a object of PhysicsEngine (JPanel Subclass) and add it into the JFrame. I add the buttons by using this which reference to the PhysicsEngine (JPanel subclass) object.
Here is the working code:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
public class PhysicsEngine extends JPanel {
double x, y;
JPanel pan;
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;
public static void main(String[] args) {
JFrame frame = new JFrame("Ball Engine");
PhysicsEngine gui = new PhysicsEngine();
frame.add(gui, BorderLayout.CENTER);
frame.setSize(600, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public PhysicsEngine() {
b1 = new JButton("1");
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
startFirst();
} catch (InterruptedException exception) {
}
}
});
this.add(b1);
b2 = new JButton("2");
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startSecond();
} catch (InterruptedException exception) {
}
}
});
this.add(b2);
b3 = new JButton("3");
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startThird();
} catch (InterruptedException exception) {
}
}
});
this.add(b3);
b4 = new JButton("4");
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startFourth();
} catch (InterruptedException exception) {
}
}
});
this.add(b4);
b5 = new JButton("5");
b5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
startFifth();
} catch (InterruptedException exception) {
}
}
});
this.add(b5);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println("" + y);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval((int) x, (int) y, 30, 30);
}
public void startFirst() throws InterruptedException {
x = 300;
for (int t = 1;; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
if (y >= 615)
break; // stops the loop when the ball is off the screen
y = .1 * t * t + 0 * t + 80; // parametric equation for y
repaint();
Thread.sleep(10);
}
}
public void startSecond() throws InterruptedException {
x = 300;
for (int t = 1;; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
if (y >= 615)
break; // stops the loop when the ball is off the screen
y = .1 * t * t - 10 * t + 550; // parametric equation for y
repaint();
Thread.sleep(10);
}
}
public void startThird() throws InterruptedException {
for (int t = 1;; t++) {
if (y >= 615 || x >= 615)
break; // stops the loop when the ball is off the screen
y = .1 * t * t - 10 * t + 550; // parametric equation for y
x = 0 * t * t + 5 * t + 50; // parametric equation for x
repaint();
Thread.sleep(10);
}
}
public void startFourth() throws InterruptedException {
for (int t = 1;; t++) {
// xPos= 0*t*t + 0*t + 300 this is constant at 300
if (y >= 615 || x >= 615)
break; // stops the loop when the ball is off the screen
y = t * t * t + 50; // given parametric equation for y
x = t - 4; // given parametric equation for x
repaint();
Thread.sleep(10);
}
}
public void startFifth() throws InterruptedException {
for (int t = 1; t < 500 /* goes for 5 seconds */; t++) {
y = 200 * Math.sin(t) + 300; // given parametric equation for y
x = 200 * Math.cos(t) + 300; // given parametric equation for x
repaint();
Thread.sleep(10);
}
}
}

I'm trying to make my image move using KeyListener but it's giving me an error?

I'm trying to make Boy1 move but in the second class I'm getting redlines under setX. Anyone know what's wrong?
First Class:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MyGame extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0, y = 0, velx =0, vely =0;
public MyGame() {
t.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x,y,50,30);
}
public void actionPerformed(ActionEvent e) {
if(x < 0)
{
velx=0;
x = 0;
}
if(x > 530)
{
velx=0;
x = 530;
}
if(y < 0)
{
vely=0;
y = 0;
}
if(y > 330)
{
vely=0;
y = 330;
}
x += velx;
y += vely;
repaint();
}
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_DOWN){
vely = 1;
velx = 0;
}
if (code == KeyEvent.VK_UP){
vely = -1;
velx = 0;
}
if (code == KeyEvent.VK_LEFT){
vely = 0;
velx = -1;
}
if (code == KeyEvent.VK_RIGHT){
vely = 0;
velx = 1;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
velx=0;
vely=0;
}
public static void main (String arge[]){
JFrame f = new JFrame();
MyGame s = new MyGame();
f.add(s);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600,400);
f.setVisible(true);
}
}
Problem is with this last class. Perhaps it needs to be KeyAdapter? But I tried that and seems like that totally doesn't work.
The compiler is flagging you for a reason -- you're trying to call methods on a variable as if it were a variable that the class contains when it isn't -- it's held by a different class. And this isn't Kosher in Java.
What you should do is give the class that holds the variable public methods that outside classes can call and that will allow outside classes to be able to move the label. Then give your control object (the listener) an instance of the class that has these methods.
As an aside, you're usually better off using Key Bindings and not using a KeyListener.
I can give you an example of code that uses Key Bindings to move a JLabel around a JPanel:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EnumMap;
import javax.imageio.ImageIO;
import javax.swing.*;
#SuppressWarnings("serial")
public class AnimateExample extends JPanel {
public static final String DUKE_IMG_PATH = // https://duke.kenai.com/iconSized/duke.gif
"https://duke.kenai.com/iconSized/duke4.gif";
private static final int PREF_W = 800;
private static final int PREF_H = 800;
private static final int TIMER_DELAY = 20;
private static final String KEY_DOWN = "key down";
private static final String KEY_RELEASE = "key release";
public static final int TRANSLATE_SCALE = 3;
private static final String BACKGROUND_STRING = "Use Arrow Keys to Move Image";
private static final Font BG_STRING_FONT = new Font(Font.SANS_SERIF,
Font.BOLD, 32);
private EnumMap<Direction, Boolean> dirMap =
new EnumMap<AnimateExample.Direction, Boolean>(Direction.class);
private BufferedImage image = null;
private int imgX = 0;
private int imgY = 0;
private int bgStringX;
private int bgStringY;
public AnimateExample() {
for (Direction dir : Direction.values()) {
dirMap.put(dir, Boolean.FALSE);
}
try {
URL imgUrl = new URL(DUKE_IMG_PATH);
image = ImageIO.read(imgUrl);
Icon icon = new ImageIcon(image);
JOptionPane.showMessageDialog(null, icon);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Timer(TIMER_DELAY, new TimerListener()).start();
// here we set up our key bindings
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition);
ActionMap actionMap = getActionMap();
for (final Direction dir : Direction.values()) {
// for the key down key stroke
KeyStroke keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0,
false);
inputMap.put(keyStroke, dir.name() + KEY_DOWN);
actionMap.put(dir.name() + KEY_DOWN, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent arg0) {
dirMap.put(dir, true);
}
});
// for the key release key stroke
keyStroke = KeyStroke.getKeyStroke(dir.getKeyCode(), 0, true);
inputMap.put(keyStroke, dir.name() + KEY_RELEASE);
actionMap.put(dir.name() + KEY_RELEASE, new AbstractAction() {
#Override
public void actionPerformed(ActionEvent arg0) {
dirMap.put(dir, false);
}
});
}
FontMetrics fontMetrics = getFontMetrics(BG_STRING_FONT);
int w = fontMetrics.stringWidth(BACKGROUND_STRING);
int h = fontMetrics.getHeight();
bgStringX = (PREF_W - w) / 2;
bgStringY = (PREF_H - h) / 2;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g.setFont(BG_STRING_FONT);
g.setColor(Color.LIGHT_GRAY);
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.drawString(BACKGROUND_STRING, bgStringX, bgStringY);
if (image != null) {
g.drawImage(image, imgX, imgY, this);
}
}
private class TimerListener implements ActionListener {
public void actionPerformed(java.awt.event.ActionEvent e) {
for (Direction dir : Direction.values()) {
if (dirMap.get(dir)) {
imgX += dir.getX() * TRANSLATE_SCALE;
imgY += dir.getY() * TRANSLATE_SCALE;
}
}
repaint();
};
}
enum Direction {
Up(KeyEvent.VK_UP, 0, -1), Down(KeyEvent.VK_DOWN, 0, 1), Left(
KeyEvent.VK_LEFT, -1, 0), Right(KeyEvent.VK_RIGHT, 1, 0);
private int keyCode;
private int x;
private int y;
private Direction(int keyCode, int x, int y) {
this.keyCode = keyCode;
this.x = x;
this.y = y;
}
public int getKeyCode() {
return keyCode;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
private static void createAndShowGui() {
AnimateExample mainPanel = new AnimateExample();
JFrame frame = new JFrame("Animate Example");
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();
}
});
}
}

Infinite background for game

I am working on a Java project to simulate the flight of a helicopter in a frame. The helicopter moves on the screen using the arrow keys. I want the helicopter to be able to move infinitely, that is, when the helicopter reaches the edge of the frame, the background should move in the opposite direction to have the effect of endless terrain.
Here is the code I have so far:
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainFrame extends JFrame
{
private static int FRAME_WIDTH = 800;
private static int FRAME_HEIGHT = 500;
public MainFrame()
{
add(new AnotherBackground(FRAME_WIDTH, FRAME_HEIGHT));
setTitle("Helicopter Background Test");
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args)
{
new MainFrame();
}
}
class AnotherBackground extends JPanel
{
private BufferedImage heliImage = null;
private BufferedImage backImage = null;
private int heliX = 0;
private int heliY = 0;
private int backX = 0;
private int backY = 0;
private int frameWidth = 0;
private int frameHeight = 0;
private int backWidth = 0;
private int backHeight = 0;
public AnotherBackground(int fWidth, int fHeight)
{
frameWidth = fWidth;
frameHeight = fHeight;
this.setFocusable(true);
this.addKeyListener(new HeliListener());
try
{
heliImage = ImageIO.read(new URL("http://imageshack.us/a/img7/2133/helicopter2f.png"));
// 2.7 Meg Crap that is a humungous image! Substitute dummy.
backImage = new BufferedImage(1918,1200,BufferedImage.TYPE_INT_RGB);
}
catch(IOException ex)
{
System.out.println("Problem durinng loading heli image");
}
backWidth = backImage.getWidth();
backHeight = backImage.getHeight();
HeliPainter l = new HeliPainter();
new Thread(l).start();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backImage, backX, backY, null);
g.drawImage(heliImage, heliX, heliY, null);
}
class HeliListener extends KeyAdapter
{
#Override
public void keyPressed(KeyEvent e)
{
System.out.println(heliX + " " + heliY + " " + backX + " " + backY);
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(heliX > 0)
{
heliX -= 5;
}
else
{
backX += 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(heliX < frameWidth)
{
heliX += 5;
}
else
{
backX -= 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
if(heliY > 0)
{
heliY -= 5;
}
else
{
backY += 5;
}
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(heliY < frameHeight)
{
heliY += 5;
}
else
{
backY -= 5;
}
}
}
}
class HeliPainter implements Runnable
{
#Override
public void run()
{
try
{
while(true)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
repaint();
}
});
Thread.sleep(1);
}
}
catch(InterruptedException ex)
{
System.out.println("Problem putting thread to sleep");
}
}
}
}
Now there's two images in the code. One is that of a small helicopter, and the other is a large (2.7 meg) background. They are here:
background
helicopter http://imageshack.us/a/img7/2133/helicopter2f.png
How to show the BG continuously?
Have a look through this source which behaves in a more predictable manner, and also includes a nice tweak to the chopper image (animated). ;)
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class MainFrame
{
public MainFrame()
{
JFrame f = new JFrame("Helicopter Background Test");
f.add(new AnotherBackground());
//setTitle("Helicopter Background Test"); Redundant..
// Set a preferred size for the content area and pack() the frame instead!
// setSize(FRAME_WIDTH,FRAME_HEIGHT);
// setLocationRelativeTo(null); Better to..
f.setLocationByPlatform(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack(); // Size the GUI - VERY MPORTANT!
f.setVisible(true);
}
public static void main(String[] args)
{
new MainFrame();
}
}
class AnotherBackground extends JPanel
{
private static int PREFERRED_WIDTH = 400;
private static int PREFERRED_HEIGHT = 200;
private BufferedImage heliImage = null;
private BufferedImage heliLeftImage = null;
private BufferedImage heliRightImage = null;
private BufferedImage backImage = null; //getFlippedImage(
private int heliX = 0;
private int heliY = 0;
private int backX = 0;
private int backY = 0;
private int frameWidth = 0;
private int frameHeight = 0;
private int backWidth = 0;
private int backHeight = 0;
public AnotherBackground()
{
frameWidth = PREFERRED_WIDTH;
frameHeight = PREFERRED_HEIGHT;
this.setFocusable(true);
this.addKeyListener(new HeliListener());
try
{
heliLeftImage = ImageIO.read(
new URL("http://imageshack.us/a/img7/2133/helicopter2f.png"));
heliRightImage = getFlippedImage(heliLeftImage);
heliImage = heliLeftImage;
// 2.7 Meg Crap that is an humungous image! Substitute dummy.
backImage = getTileImage(250);
//ImageIO.read(
// new URL("http://i.stack.imgur.com/T5uTa.png"));
backWidth = backImage.getWidth();
backHeight = backImage.getHeight();
//HeliPainter l = new HeliPainter(); // see mention of repaint()
//new Thread(l).start();
} catch(IOException ex) {
// THERE IS NO POINT CONTINUING AFTER THIS POINT!
// unless it is to pop an option pane error message..
System.err.println("Problem during loading heli image");
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT);
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
int normalizeX = (heliRealX-heliX)%backImage.getWidth();
int normalizeY = (heliRealY-heliY)%backImage.getHeight();
int timesRepeatX = (getWidth()/backImage.getWidth())+2;
int timesRepeatY = (getHeight()/backImage.getHeight())+2;
for (int xx=-1; xx<timesRepeatX; xx++) {
for (int yy=-1; yy<timesRepeatY; yy++) {
g.drawImage(
backImage,
(xx*backImage.getWidth())-normalizeX,
(yy*backImage.getHeight())-normalizeY,
this); // A JPanel IS AN ImageObserver!
g.drawImage(heliImage, heliX, heliY, this);
}
}
g.setColor(Color.BLACK);
}
private int heliRealX = 0;
private int heliRealY = 0;
class HeliListener extends KeyAdapter
{
#Override
public void keyPressed(KeyEvent e)
{
int pad = 5;
if (e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(heliX > 0)
{
heliX -= 5;
}
else
{
backX += 5;
}
heliRealX-=5;
heliImage = heliLeftImage;
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT)
{
// correct for image size + padding
if(heliX+heliImage.getWidth()+pad < getWidth())
{
heliX += 5;
}
else
{
backX -= 5;
}
heliRealX+=5;
heliImage = heliRightImage;
}
else if (e.getKeyCode() == KeyEvent.VK_UP)
{
if(heliY > 0)
{
heliY -= 5;
}
else
{
backY += 5;
}
heliRealY-=5;
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN)
{
// correct for image size + padding
if(heliY+heliImage.getHeight()+pad < getHeight())
{
heliY += 5;
}
else
{
backY -= 5;
}
heliRealY+=5;
}
repaint(); // Replaces need for threads for this simple demo!
}
}
public BufferedImage getFlippedImage(BufferedImage original) {
BufferedImage bi = new BufferedImage(
original.getWidth(),
original.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
AffineTransform at = AffineTransform.getTranslateInstance(bi.getWidth(),1d);
at.concatenate(AffineTransform.getScaleInstance(-1d,1d));
g.setTransform(at);
g.drawImage(original,0,0,this);
g.dispose();
return bi;
}
public BufferedImage getTileImage(int s) {
BufferedImage bi = new BufferedImage(s,s,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bi.createGraphics();
GradientPaint gp1 = new GradientPaint(
(float)0,(float)s/4, Color.YELLOW,
(float)s/4,0f, Color.GREEN,
true);
g.setPaint(gp1);
g.fillRect(0,0,s,s);
int trans = 165;
GradientPaint gp2 = new GradientPaint(
(float)s/2,(float)s/2, new Color(255,0,0,trans),
0f,(float)s/2, new Color(255,255,255,trans),
true);
g.setPaint(gp2);
g.fillRect(0,0,s,s);
g.dispose();
return bi;
}
}
This is a really simple example (you can only move in a single direction). The basic idea is that there is a prepareView method that is responsible for generating a view of the world based on the available viewable area. If the view is trying to view an area off the map, the map is titled to make up for it.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class InfiniteBackground {
public static void main(String[] args) {
new InfiniteBackground();
}
public InfiniteBackground() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class TestPane extends JPanel {
protected static final int DELTA = 5;
private BufferedImage terrian;
private BufferedImage heli;
private Point pov;
private Point heliPoint;
private BufferedImage view;
public TestPane() {
pov = new Point();
heliPoint = new Point();
try {
terrian = ImageIO.read(getClass().getResource("/terrain_map.jpg"));
heli = ImageIO.read(getClass().getResource("/helicopter2f.png"));
pov.x = terrian.getWidth() - getPreferredSize().width;
pov.y = ((terrian.getHeight() - getPreferredSize().height) / 2);
heliPoint.x = getPreferredSize().width / 2;
heliPoint.y = getPreferredSize().height / 2;
prepareView();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "goLeft");
am.put("goLeft", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
heliPoint.x -= DELTA;
if (heliPoint.x - (heli.getWidth() / 2) < 0) {
heliPoint.x = (heli.getWidth() / 2);
prepareView();
pov.x -= DELTA;
}
repaint();
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 200);
}
protected void prepareView() {
if (getWidth() > 0 && getHeight() > 0) {
view = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = view.createGraphics();
if (pov.x < 0) {
pov.x = terrian.getWidth();
}
g2d.drawImage(terrian, -pov.x, -pov.y, this);
if (pov.x + getWidth() > terrian.getWidth()) {
g2d.drawImage(terrian, -pov.x + terrian.getWidth(), -pov.y, this);
}
g2d.dispose();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (terrian != null) {
Graphics2D g2d = (Graphics2D) g.create();
if (view == null) {
prepareView();
}
g2d.drawImage(view, 0, 0, this);
g2d.drawImage(heli, heliPoint.x - (heli.getWidth() / 2), heliPoint.y - (heli.getHeight() / 2), this);
g2d.dispose();
}
}
}
}

Smooth out Java paint animations

I would like to make my app draw moving image a little smoother than how it is currently drawing them. I am not sure what to do to do that.
This is what my main game Thread looks like:
#Override
public void run(){
int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
Car car = new Car();
int speed = (int)(3 + Math.floor(Math.random() * (6 - 3)));
car.setSpeed(speed);
MainLoop.this.gameObjects.vehicles.add(car.create("/Media/Graphics/blueCar.png", width - 20, 78));
car.driveTo(0, 78);
}
};
new Timer(delay, taskPerformer).start();
try{
while(true){
this.repaint();
for(GameObject go : this.gameObjects.vehicles){
// loops through objects to move them
Vehicle vh = (Vehicle) go;
this.moveVehicle(vh);
if(vh.getX() <= vh.getDestX()){
vh.markForDeletion(true);
}
}
this.gameObjects.destroyVehicles();
Thread.sleep(1);
}
}catch(Exception e){
e.printStackTrace();
}
}
This is a method that calculates the items next x/y position
protected void moveVehicle(Vehicle vh){
int cx = vh.getX();
int dx = vh.getDestX();
int cy = vh.getY();
int dy = vh.getDestY();
// move along x axis
// getMaxSpeed() = Number between 3 and 6
if(cx > dx && vh.movingX() == -1){
vh.setX(cx - vh.getMaxSpeed());
}else if(cx < dx && vh.movingX() == 1){
vh.setX(cx + vh.getMaxSpeed());
}else{
vh.setX(dx);
}
// move along y axis
// getMaxSpeed() = Number between 3 and 6
if(cy > dy && vh.movingY() == -1){
vh.setY(cy - vh.getMaxSpeed());
}else if(cy < dy && vh.movingY() == 1){
vh.setY(cy + vh.getMaxSpeed());
}else{
vh.setY(dy);
}
}
This is my paint method:
#Override
public void paintComponent(Graphics graphics){
super.paintComponent(graphics);
Graphics2D g = (Graphics2D) graphics;
for(GameObject go : gameObjects.vehicles){
g.drawImage(go.getSprite(), go.getX(), go.getY(), this);
}
}
This is possibly more info than needed, but I would like to know, what should I do to make items move from left -> right top -> bottom as smoothly as possible, without much of a performance loss?
Edit: Requested sscce:
package sscce;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Sscce extends JPanel implements Runnable{
ArrayList<Square> squares = new ArrayList<>();
public Sscce(){
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(this);
Thread t = new Thread(this);
t.start();
}
public static void main(String[] args){
new Sscce();
}
#Override
public void run(){
int delay = 500; //milliseconds
ActionListener taskPerformer = new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
Square squ = new Square();
Sscce.this.squares.add(squ);
squ.moveTo(0);
}
};
new Timer(delay, taskPerformer).start();
while(true){
try{
for(Square s : this.squares){
int objX = s.getX();
int desX = s.getDestX();
if(objX <= desX){
System.out.println("removing");
this.squares.remove(s);
}else{
s.setX(s.getX() - 10);
}
}
this.repaint();
Thread.sleep(30);
}catch(Exception e){
}
}
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for(Square s : squares){
g.setColor(Color.blue);
g.fillRect(s.getX(), s.getY(), 50, 50);
}
}
}
class Square{
public int x = 0, y = 0, destX = 0;
public Square(){
this.x = 400;
this.y = 100;
}
public void moveTo(int destX){
this.destX = destX;
}
public int getX(){
return this.x;
}
public int getDestX(){
return this.destX;
}
public void setX(int x){
this.x = x;
}
public int getY(){
return this.y;
}
}
First note, for some reason, I had issues with the JPanel implementing Runnable when running it under MacOS - I have no idea why, but that's why I moved it out.
It is possible for your squares to be update while it is been used to paint which will cause an exception (also, removing elements from a list while you're iterating it isn't a good idea either ;))
Instead, I have two lists. I have a model, which the list can modify and then the paint list which the paint method can use. This allows the thread to modifiy the model, while a paint process is underway.
To prevent any clash, I've added in a lock, which prevents one thread from modifying/accessing the paint list, while another thread has it locked.
Now. Down to the real problem. The main issue you're having isn't the amount of time between the updates, but the distance you are moving. Reduce the distance (to make it slower) and standarise the updates.
Most people won't notice anything much over 25fps, so trying to do much more then that is just wasting CPU cycles and starving the repaint manager, preventing it from actually updating the screen.
It's a balancing act to be sure...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestAnimation11 extends JPanel {
private ArrayList<Square> squares = new ArrayList<>();
private ReentrantLock lock;
public TestAnimation11() {
lock = new ReentrantLock();
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(TestAnimation11.this);
Thread t = new Thread(new UpdateEngine());
t.start();
}
});
}
public static void main(String[] args) {
new TestAnimation11();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Square[] paint = null;
lock.lock();
try {
paint = squares.toArray(new Square[squares.size()]);
} finally {
lock.unlock();
}
for (Square s : paint) {
g.setColor(Color.blue);
g.fillRect(s.getX(), s.getY(), 50, 50);
}
}
public class UpdateEngine implements Runnable {
private List<Square> model = new ArrayList<>(squares);
#Override
public void run() {
int ticks = 0;
List<Square> dispose = new ArrayList<>(25);
while (true) {
ticks++;
dispose.clear();
for (Square s : model) {
int objX = s.getX();
int desX = s.getDestX();
if (objX <= desX) {
dispose.add(s);
} else {
s.setX(s.getX() - 2);
}
}
model.removeAll(dispose);
if (ticks == 11) {
Square sqr = new Square();
sqr.moveTo(0);
model.add(sqr);
} else if (ticks >= 25) {
ticks = 0;
}
lock.lock();
try {
squares.clear();
squares.addAll(model);
} finally {
lock.unlock();
}
repaint();
try {
Thread.sleep(40);
} catch (Exception e) {
}
}
}
}
class Square {
public int x = 0, y = 0, destX = 0;
public Square() {
this.x = 400;
this.y = 100;
}
public void moveTo(int destX) {
this.destX = destX;
}
public int getX() {
return this.x;
}
public int getDestX() {
return this.destX;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return this.y;
}
}
}

Categories