I'm trying to make a simple program that shows that lets an image bob across the screen.
Now iv'e succeded to make an image to go form left to right but now I have like 20 images on the screen.
What I need to get is that when the next image is printed that te previous image is hidden. Also if someone could help me out with printing with a timer it would be great.
Here is my code
package imagemove;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class imagemove extends Component {
private int x;
private int y;
BufferedImage img;
public imagemove() {
try {
img = ImageIO.read(new File("F:/JAVA/workspace/Tutorials/src/imagemove/1.jpg"));
} catch (IOException e) {
}
}
public void paint(Graphics g) {
x = 0;
y = 50;
for (int number = 1; number <= 15; number++) {
g.drawImage(img, x, y, this);
if (x > 1000) {
x = 0;
} else {
x += 100;
}
if(y > 100) {
y -= 100;
} else {
y += 25;
}
repaint();
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Boot");
f.setSize(1000,1000);
f.add(new imagemove());
f.setVisible(true);
}
}
you should put your for-loop in another method, which is called from the main method. (the draw image instruction should remain in the paint mathod obviously)
use paintComponent instead of paint
put super.paintComponent(g) as the first line in paintComponent(). and your previous images should be cleared
Edit:
extend JComponent instead of Component. Component is AWT, JComponent is Swing
It works this way; it tested it:
public class imagemove extends Component {
private int x;
private int y;
BufferedImage img;
public imagemove() {
try {
img = ImageIO.read(new File("F:/JAVA/workspace/Tutorials/src/imagemove/1.jpg"));
} catch (IOException e) {
}
x = 0;
y = 50;
}
#Override
public void paint(Graphics g) {
g.drawImage(img, x, y, this);
if (x > 1000) {
x = 0;
} else {
x += 100;
}
if(y > 100) {
y -= 100;
} else {
y += 25;
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Boot");
f.setSize(1000,1000);
f.add(new imagemove());
f.setVisible(true);
for (int number = 1; number <= 15; number++) {
f.repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
}
You can't call repaint from within the paint() method.
Related
I have a basic program that renders the position of the mouse on a java.awt.Canvas. However, the further away the mouse gets from the coordinates 0, 0 (top left of the window) the more inaccurate it becomes.
The box drawn on the screen (that represents the mouse position) seems to increasingly fall further and further behind where the actual mouse position is. Is there something I haven't done right or is this a problem with AWT or Swing.
Here's my code:
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
public class Main extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
private BufferedImage image;
private int[] pixels;
private static final MouseHandler handler = new MouseHandler();
public Main() {
image = new BufferedImage(640, 480, BufferedImage.TYPE_INT_RGB);
pixels = ((DataBufferInt)image.getRaster().getDataBuffer()).getData();
initWindow();
addMouseMotionListener(handler);
start();
}
private void initWindow() {
Dimension d = new Dimension(image.getWidth(), image.getHeight());
JFrame f = new JFrame("Mouse Pointer");
f.setPreferredSize(d);
f.setMinimumSize(d);
f.setMaximumSize(d);
f.setVisible(true);
f.setResizable(false);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void start() {
new Thread(this).start();
}
private void render() {
BufferStrategy bs = getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
clearScreen();
drawMousePos();
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
g.dispose();
bs.show();
}
public void run() {
while(true) {
render();
}
}
private void clearScreen() {
for(int i = 0; i < pixels.length; i++) pixels[i] = 0;
}
//draw 3 by 3 box around mouse position
private void drawMousePos() {
for(int y = -1; y <= 1; y++) {
for(int x = -1; x <= 1; x ++) {
if((handler.x + x) >= 0 &&
(handler.x + x) <= image.getWidth() &&
(handler.y + y) >= 0 &&
(handler.y + y) <= image.getHeight())
pixels[(handler.x + x) + (handler.y + y) * image.getWidth()] = 0xff00ff00;
}
}
}
public static void main(String[] args) {
new Main();
}
}
Mouse Handler class:
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
public class MouseHandler implements MouseMotionListener {
public int x, y;
public void mouseDragged(MouseEvent e) {
x = e.getX();
y = e.getY();
}
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
}
}
Thanks for any help in advance.
The problem here is that you're setting size of the whole frame, ie 480 - it is the height of window with title bar, this is why actual size of content pane is smaller (~455), then during painting you're down scaling image.
To fix this - set content pane size to desired one:
f.getContentPane().setPreferredSize(d);
f.getContentPane().setMinimumSize(d);
f.getContentPane().setMaximumSize(d);
You also have small bug in drawMousePos:
(handler.x + x) <= image.getWidth() should use < instead of <=
I've been trying to make a for loop that horizontally replicates vertical lines across the screen, each the same distance apart from its precedent; however, my code doesn't seem to work despite appearing to be syntactically correct. I've posted my code below, hopefully someone can identify the problem.
class HVLines
{
public static void Lines(Graphics g)
{
int k;
int x=0;
for (k = 1; k <= 50; k++)
{
g.drawLine(20+x,150,20+x,525);
for (x = 1; x <= 50; x+=20)
{
}
}
}
}
It should look like this. I can't ensure it will work since I don't know how you use it. Also, in your loops, you use x twice, but don't use k. Change one of those, or , if you don't need it, erase one of the loops.
I am prett sure this one creates a diagonal line, not horizontal.
for (k = 1; k <= 50; k++) {
for (x = 1; x <= 50; x+=20) {
// Choose one of the following
g.drawLine(20+k,150,20+x,525);
g.drawLine(20+x,150,20+k,525);
}
}
This one creates a straight line:
for (x = 1; x <= 50; x+=20) {
g.drawLine(20+x,150,20+x,525);
}
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Line2D;
import javax.swing.JApplet;
import javax.swing.JFrame;
public class DrawLine extends JApplet {
public void init() {
setBackground(Color.white);
setForeground(Color.white);
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.gray);
for (int y = 0; y <= 300; y += 30) {
g2.draw(new Line2D.Double(0, y, 300, y));
}
}
public static void main(String s[]) {
JFrame f = new JFrame("Line");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JApplet applet = new DrawLine();
f.getContentPane().add("Center", applet);
applet.init();
f.pack();
f.setSize(new Dimension(300, 300));
f.setVisible(true);
}
}
I honestly don't know what I'm doing wrong. (Although I'm sure it's quite a bit.) I've been trying to adjust my code for hours to no avail.
I'm attempting to cut up pieces of a picture and display them. Later, I will randomize where they are located and try to place them in their correct positions. Now, however, I'm having issues having anything show up on my JPanel at all. At one point, my test code displayed the image. Now, however, the same test code doesn't work.
If you can see what I'm doing wrong/where the issue is, please let me know. Hopefully it's something simple and stupid.
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;
public class Lab10 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
MyFrame frame = new MyFrame();
MyPanel panel = new MyPanel();
frame.add(panel);
panel.setFocusable(true);
}
}
class MyFrame extends JFrame{
MyFrame(){
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setSize(800,800);
setResizable(false);
}
}
class MyPanel extends JPanel{
public static final int SIZE = 4;
private int oldx = -1;
private int oldy = -1;
private final String fileName = "houseTyrell.png";
public ImageArray imageArray = new ImageArray(fileName, SIZE);
MyPanel(){
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if(e.getButton()==1){
if(oldx == -1){
oldx = e.getX();
oldy = e.getY();
}else{
//imageArray.swapPoints(oldx, oldy, e.getX(), e.getY());
oldx = -1;
oldy = -1;
repaint();
}
}
}
});
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
imageArray.draw(g2);
/*Image image2;
try {
image2 = ImageIO.read(new File("houseTyrell.png"));
System.out.println("I should print");
try{
g2.drawImage(image2, 0, 0, null);
} catch(Exception my){
System.out.println("Drawing issue");
}
} catch (IOException ex) {
System.out.println("Reading issue");
}*/
}
}
class ImageArray{
private Square[][] squares;
private String fileName;
private int size;
private int w;
private int h;
public ImageArray(String fileName, int size) {
this.size = size;
this.fileName= fileName;
squares = new Square[size][size];
try {
BufferedImage image = ImageIO.read(new File(fileName));
w = image.getWidth() / size;
h = image.getHeight() / size;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
squares[row][col] = new Square(
image.getSubimage(row * w , col * h , w, h), row, col, w, h);
}
}
} catch (Exception e) {
System.out.println("Can't open file!");
}
shuffle();
}
//TODO
public void shuffle(){
for(int i = 0; i < size * size; i++){
}
}
//TODO
public void swapPoints(int oldx, int oldy, int newx, int newy){
}
public void draw(Graphics2D g2){
for(int i = 0; i < squares.length; i++){
for(int j = 0; j < squares[0].length; j++){
Square square = squares[i][j];
square.draw(g2);
}
}
}
}
class Square{
private BufferedImage image;
private int row;
private int col;
private int x,y;
private int w;
private int h;
Square(BufferedImage image, int row, int col, int w, int h){
this.image = image;
this.row = row;
this.col = col;
this.x = row * w;
this.y = col * h;
this.w = w;
this.h = h;
}
public void draw(Graphics2D g2){
try{
g2.drawImage(image, x, y, null);
} catch (Exception my){
System.out.println("Square issue");
}
}
public BufferedImage getImage(){
return image;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
}
}
You are making the frame visible BEFORE you've finished establishing UI, try calling invalidate, validate and repaint on the frame AFTER you've added the panel...
public static void main(String[] args) {
MyFrame frame = new MyFrame();
MyPanel panel = new MyPanel();
frame.add(panel);
panel.setFocusable(true);
frame.invalidate();
frame.validate();
frame.repaint();
}
Frankly, your MyFrame class is doing very little (other then making your life more difficult), I'd consider getting rid of it, maybe replace it with a builder method which returns a frame which is not visible yet...
You should also be creating your UI from within the context of the Event Dispatching Thread, which can help solve other "weird" issues.
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
MyFrame frame = new MyFrame();
MyPanel panel = new MyPanel();
frame.add(panel);
panel.setFocusable(true);
frame.invalidate();
frame.validate();
frame.repaint();
}
});
}
See Initial Threads for more details
In the main method of Class Lab10, initialize the JPanel before the JFrame and it should work.
PS: Make sure the image referenced "houseTyrell.png" exists or use a fully qualified path temporarily for testing (i.e. c://test//houseTyrell.png).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I created a GUI named Menu class for my Start, Help and Exit button. my problem is my game won't start, it hangs everytime I press the Start button. Can someone check my error and explain it to me because its my case study at school.
package spaceSip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Menu extends JFrame implements ActionListener
{
private JLabel titleL;
private JButton startB, helpB, exitB;
static JFrame frame1 = new JFrame();
public Menu()
{
frame1.setSize(500,250);
Container mainP = frame1.getContentPane();
mainP.setLayout(null);
titleL = new JLabel("WELCOME");
startB = new JButton("Start");
helpB = new JButton("Help");
exitB = new JButton("Exit");
mainP.add(titleL);
titleL.setFont(new Font("Chiller",Font.BOLD,50));
titleL.setBounds(100, 30, 200, 50);
mainP.add(startB);
startB.setMnemonic(KeyEvent.VK_S);
startB.setBounds(200, 80, 100, 20);
mainP.add(helpB);
helpB.setMnemonic(KeyEvent.VK_H);
helpB.setBounds(200, 100, 100, 20);
mainP.add(exitB);
exitB.setMnemonic(KeyEvent.VK_E);
exitB.setBounds(200, 120, 100, 20);
startB.addActionListener(this);
helpB.addActionListener(this);
exitB.addActionListener(this);
frame1.setVisible(true);
frame1.setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
String key = e.getActionCommand();
if(key == "Start")
{
frame1.dispose();
new SpaceShipMain();
}
else if(key == "Help")
{
}
else
System.exit(0);
}
public static void main(String[]args)
{
new Menu();
}
}
package spaceSip;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SpaceShipMain implements MouseListener
{
private JFrame background;
private SpaceShipPanel back;
public static boolean paused;
public static boolean crashed;
public static boolean started;
public static boolean playedOnce;
public boolean goingUp;
private double upCount;
public static int distance;
public static int maxDistance;
public final int XPOS;
public final int NUMRECS;
public final int RECHEIGHT;
public final int RECWIDTH;
private int moveIncrement;
private int numSmoke;
private ArrayList<SpaceShipImage> toprecs;
private ArrayList<SpaceShipImage> bottomrecs;
private ArrayList<SpaceShipImage> middlerecs;
private ArrayList<SpaceShipImage> smoke;
private SpaceShipImage helicopter;
public SpaceShipMain()
{
NUMRECS = 100;
RECHEIGHT = 70;
RECWIDTH = 30;
XPOS = 200;
playedOnce = false;
maxDistance = 0;
load(new File("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/Best.txt"));
initiate();
}
public void load(File file)
{
try
{
Scanner reader = new Scanner(file);
while(reader.hasNext())
{
int value = reader.nextInt();
if(value > maxDistance)
maxDistance = value;
}
}
catch(IOException i )
{
System.out.println("Error. "+i);
}
}
public void save()
{
FileWriter out;
try
{
out = new FileWriter("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/Best.txt");
out.write("" + maxDistance);
out.close();
}
catch(IOException i)
{
System.out.println("Error: "+i.getMessage());
}
}
public void initiate()
{
if(!playedOnce)
{
background = new JFrame("Space Ship Game");
background.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //closes the program when the window is closed
background.setResizable(false); //don't allow the user to resize the window
background.setSize(new Dimension(800,500));
background.setVisible(true);
back = new SpaceShipPanel("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/starfield.jpg");
background.add(back);
back.addMouseListener(this);
}
playedOnce = true;
goingUp = false;
paused = false;
crashed = false;
started = false;
distance = 0;
upCount = 0;
moveIncrement = 2;
numSmoke = 15;
toprecs = new ArrayList<SpaceShipImage>();
middlerecs = new ArrayList<SpaceShipImage>();
bottomrecs = new ArrayList<SpaceShipImage>();
smoke = new ArrayList<SpaceShipImage>();
helicopter = new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF",XPOS,200);
for(int x = 0; x < NUMRECS; x++)
toprecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,5));
for(int x = 0; x < NUMRECS; x++)
bottomrecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,410));
middlerecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid2.jpg",1392,randomMidHeight()));
middlerecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid2.jpg",1972,randomMidHeight()));
drawRectangles();
}
public void drawRectangles()
{
long last = System.currentTimeMillis();
long lastCopter = System.currentTimeMillis();
long lastSmoke = System.currentTimeMillis();
long lastSound = System.currentTimeMillis();
int firstUpdates = 0;
double lastDistance = (double)System.currentTimeMillis();
while(true)
{
if(!paused && !crashed && started && (double)System.currentTimeMillis() - (double)(2900/40) > lastDistance)
{
lastDistance = System.currentTimeMillis();
distance++;
}
if(!paused && !crashed && started && System.currentTimeMillis() - 10 > lastCopter)
{
lastCopter = System.currentTimeMillis();
updateCopter();
updateMiddle();
}
if(!paused && !crashed && started && System.currentTimeMillis() - 100 > last)
{
last = System.currentTimeMillis();
updateRecs();
}
if(!paused && !crashed && started && System.currentTimeMillis() - 75 > lastSmoke)
{
lastSmoke = System.currentTimeMillis();
if (firstUpdates < numSmoke)
{
firstUpdates++;
smoke.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",187,helicopter.getY()));
for(int x = 0; x < firstUpdates; x++)
smoke.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",smoke.get(x).getX() - 12, smoke.get(x).getY()));
}
else
{
for(int x = 0; x < numSmoke - 1; x++)
smoke.get(x).setY(smoke.get(x+1).getY());
smoke.set(numSmoke - 1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",187,helicopter.getY()));
}
}
back.updateImages(middlerecs,helicopter,smoke);
}
}
public void updateRecs()
{
for(int x = 0; x < (NUMRECS - 1); x++) //move all but the last rectangle 1 spot to the left
{
toprecs.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,toprecs.get(x+1).getY()));
bottomrecs.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,bottomrecs.get(x+1).getY()));
}
}
public void randomDrop()
{
toprecs.get(26).setY(toprecs.get(26).getY() + (463 - bottomrecs.get(26).getY()));
bottomrecs.get(26).setY(463);
}
public int randomMidHeight()
{
int max = 10000;
int min = 0;
for(int x = 0; x < NUMRECS; x++)
{
if(toprecs.get(x).getY() > min)
min = (int)toprecs.get(x).getY();
if(bottomrecs.get(x).getY() < max)
max = (int)bottomrecs.get(x).getY();
}
min += RECHEIGHT;
max -= (RECHEIGHT + min);
return min + (int)(Math.random() * max);
}
//moves the randomly generated middle rectangles
public void updateMiddle()
{
if(middlerecs.get(0).getX() > -1 * RECWIDTH)
{
middlerecs.set(0,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(0).getX() - (RECWIDTH/5), middlerecs.get(0).getY()));
middlerecs.set(1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(1).getX() - (RECWIDTH/5), middlerecs.get(1).getY()));
}
else
{
middlerecs.set(0,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(1).getX() - (RECWIDTH/5), middlerecs.get(1).getY()));
middlerecs.set(1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(0).getX() + 580,randomMidHeight()));
}
}
public boolean shoot()
{
for(int x = 3; x <= 7; x++)
if(helicopter.getY() >= bottomrecs.get(x).getY())
return true;
for(int y = 3; y <= 7; y++)
if(helicopter.getY() <= toprecs.get(y).getY())
return true;
for(int z = 0; z <= 1; z++)
if(isInMidRange(z))
return true;
return false;
}
public boolean isInMidRange(int num)
{
Rectangle middlecheck = new Rectangle((int)middlerecs.get(num).getX(),(int)middlerecs.get(num).getY(),RECWIDTH,RECHEIGHT);
Rectangle coptercheck = new Rectangle((int)helicopter.getX(),(int)helicopter.getY(),70,48); //asteroid X and y bump
return middlecheck.intersects(coptercheck);
}
public void crash()
{
crashed = true;
if(distance > maxDistance)
{
maxDistance = distance;
save();
}
int reply = JOptionPane.showConfirmDialog(null, " RESTART ?", "GAME OVER", JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION)
initiate();
else
System.exit(0);
initiate();
}
//moves the spaceship
public void updateCopter()
{
upCount += .10;
if(goingUp)
{
if(upCount < 3.5)
helicopter.setPosition(XPOS,(double)(helicopter.getY() - (.3 + upCount)));
else
helicopter.setPosition(XPOS,(double)(helicopter.getY() - (1.2 + upCount)));
helicopter.setImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF");
}
else
{
if(upCount < 1)
helicopter.setPosition(XPOS,(double)(helicopter.getY() + upCount));
else
helicopter.setPosition(XPOS,(double)(helicopter.getY() + (1.2 + upCount)));
helicopter.setImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF");
}
if(shoot())
crash();
}
//Called when the mouse exits the game window
public void mouseExited(MouseEvent e)
{
paused = true;
}
//Called when the mouse enters the game window
public void mouseEntered(MouseEvent e)
{
}
//Called when the mouse is released
public void mouseReleased(MouseEvent e)
{
goingUp = false;
upCount = -1;
if(paused)
paused = false;
}
//Called when the mouse is pressed
public void mousePressed(MouseEvent e)
{
if (!started)
started = true;
goingUp = true;
upCount = 0;
}
//Called when the mouse is released
public void mouseClicked(MouseEvent e)
{
}
}
package spaceSip;
import java.awt.Image;
import javax.swing.ImageIcon;
public class SpaceShipImage
{
private Image image; //The picture
private double x; //X position
private double y; //Y position
//Construct a new Moving Image with image, x position, and y position given
public SpaceShipImage(Image img, double xPos, double yPos)
{
image = img;
x = xPos;
y = yPos;
}
//Construct a new Moving Image with image (from file path), x position, and y position given
public SpaceShipImage(String path, double xPos, double yPos)
{
this(new ImageIcon(path).getImage(), xPos, yPos);
//easiest way to make an image from a file path in Swing
}
//They are set methods. I don't feel like commenting them.
public void setPosition(double xPos, double yPos)
{
x = xPos;
y = yPos;
}
public void setImage(String path)
{
image = new ImageIcon(path).getImage();
}
public void setY(double newY)
{
y = newY;
}
public void setX(double newX)
{
x = newX;
}
//Get methods which I'm also not commenting
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public Image getImage()
{
return image;
}
}
package spaceSip;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
class SpaceShipPanel extends JPanel
{
private Image background;
private ArrayList<SpaceShipImage> middle;
private SpaceShipImage copter;
private ArrayList<SpaceShipImage> smoke;
//Constructs a new ImagePanel with the background image specified by the file path given
public SpaceShipPanel(String img)
{
this(new ImageIcon(img).getImage());
//The easiest way to make images from file paths in Swing
}
//Constructs a new ImagePanel with the background image given
public SpaceShipPanel(Image img)
{
background = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
//Get the size of the image
//Thoroughly make the size of the panel equal to the size of the image
//(Various layout managers will try to mess with the size of things to fit everything)
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
middle = new ArrayList<SpaceShipImage>();
smoke = new ArrayList<SpaceShipImage>();
}
//This is called whenever the computer decides to repaint the window
//It's a method in JPanel that I've overwritten to paint the background and foreground images
public void paintComponent(Graphics g)
{
//Paint the background with its upper left corner at the upper left corner of the panel
g.drawImage(background, 0, 0, null);
//Paint each image in the foreground where it should go
for(SpaceShipImage img : middle)
g.drawImage(img.getImage(), (int)(img.getX()), (int)(img.getY()), null);
for(SpaceShipImage img : smoke)
g.drawImage(img.getImage(), (int)(img.getX()), (int)(img.getY()), null);
if(copter != null)
g.drawImage(copter.getImage(), (int)(copter.getX()), (int)(copter.getY()), null);
drawStrings(g);
}
public void drawStrings(Graphics g)
{
g.setColor(Color.WHITE);
g.setFont(new Font("Arial",Font.BOLD,20));
g.drawString("Distance: " + SpaceShipMain.distance,30,440);
g.setFont(new Font("Arial",Font.BOLD,20));
if (SpaceShipMain.distance > SpaceShipMain.maxDistance)
g.drawString("Best: " + SpaceShipMain.distance,650,440);
else
g.drawString("Best: " + SpaceShipMain.maxDistance,650,440);
if(SpaceShipMain.paused)
{
g.setFont(new Font("Chiller",Font.BOLD,72));
g.drawString("Paused",325,290);
g.setFont(new Font("Chiller",Font.BOLD,30));
g.drawString("Click to unpause.",320,340);
}
}
//Replaces the list of foreground images with the one given, and repaints the panel
public void updateImages(ArrayList<SpaceShipImage> newMiddle,SpaceShipImage newCopter,ArrayList<SpaceShipImage> newSmoke)
{
copter = newCopter;
middle = newMiddle;
smoke = newSmoke;
repaint(); //This repaints stuff... you don't need to know how it works
}
}
You compare Strings with equals(value equality) not with ==(reference equality). For more information read this previous question How do I compare strings in Java?
As #AndrewThompson always advice don't use NullLayout
Java GUIs might have to work on a number of platforms, on different
screen resolutions & using different PLAFs. As such they are not
conducive to exact placement of components. To organize the
components for a robust GUI, instead use layout managers, or
combinations of
them1, along
with layout padding & borders for white
space2.
As you say that your gui is blocked, that may be cause some of your execution code takes too more time and it's executed in the same thread as gui stuff (The Event Dispatch Thread). As you have a while(true) that's block the gui so use a SwingTimer for execute repeatidly task or if that code that takes long time execute it in a background thread using a Swing Worker. Here you have a complete example. When you perform custom painting you should override paintComponent and in first line you have to call super.paintComponent(..) to follow correct chaining. Read more in Painting in AWT-Swing.
Another error i see is that you are adding components after calling setVisible(true) without calling revalidate() repaint(). So i recommend to first add components to container then call setVisible(true) at final step.
Hi I am trying to make a red box appear at the bottom of a JPanel .I wish for this box to move to one corner of the screen and stop and then start moving the other way,however i have been unable make the box stop the following is the code i have been working with
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
public class JavaApplication13 extends JPanel {
public static void main(String[] args) {
JFrame rough = new JFrame("Panamr");
rough.setVisible(true);
rough.setLocation(1, 1);
rough.setSize(500, 500);
rough.setContentPane(mamals);
}
public static int iomega(int x, int y) {
if (y == 1) {
diget = -5;
time.stop();
}
if (y == 0) {
diget = 5;
}
return diget;
}
static JavaApplication13 mamals = new JavaApplication13();
JavaApplication13() {
setBackground(Color.red);
}
static int oy = 400;
static int ox = 200;
static int diget;
static Timer time = new Timer(100, new ActionListener() {
public int xy = 1;
#Override
public void actionPerformed(ActionEvent e) {
iomega(ox, xy);
if (ox == 500) {
xy = 1;
}
if (ox == 0) {
xy = 0;
}
ox = ox - iomega(ox, oy);
/*if(ox!=500){
ox=ox-diget;
if(ox==0){
diget=-5;}
else {
diget=5;
}
}*/
}
});
boolean test = true;
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.fillRect(ox, oy, 60, 60);
time.start();
repaint();
}
}
your co-ordiantes for the frames/panels size is off, you should calculate this dynamically maybe, or have a final value. Next your xy=0 and xy=1 should be swapped like this:
if (ox == 400) {//this was a larger number then the panel/frame so it went offscreen
xy = 0;//swapped
}
if (ox == 0) {
xy = 1;//swapped
}