I recently was playing around with Java, and I made a program that runs in a loop. When I tried hitting the X in the corner to close it, nothing happened. I tried adding standard mouselistener code to make it exit, but it won't come through the loop. The program is simply a small square bouncing around the screen:
package mainPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import javax.swing.*;
public class MainClass extends JApplet{
public static boolean isRunning = true;
public static void startStop(){
if(isRunning){
isRunning = false;
} else {
isRunning = true;
}
}
/**
* Eclipse kept yelling at me.
*/
private static final long serialVersionUID = -3997547128895841169L;
final static Color bg = Color.white;
final static Color fg = Color.black;
/*
* The direction of the box; 1 is up-right, 2 is down-right, etc.
*/
public static byte direction = 1;
/*
*The X and Y values start somewhat randomly.
*/
public static short x = (short) (Math.random() * 150);
public static short y = (short) (Math.random() * 150);
public void init() {
}
public static void moveBall(){
if(x >= 585){
if(direction == 1){
direction = 4;
} else {
direction = 3;
}
} else if(x <= 0){
if(direction == 3){
direction = 2;
} else {
direction = 1;
}
} else if(y <= 0){
if(direction == 1){
direction = 2;
} else {
direction = 3;
}
} else if(y >= 365){
if(direction == 3){
direction = 4;
} else {
direction = 1;
}
}
if(direction == 1){
x++; y--;
} else if(direction == 2){ x++; y++;
} else if(direction == 3){ x--; y++;
} else if(direction == 4){ x--; y--;
} else { System.out.println(direction); System.exit(5);}
}
public void paint(Graphics g){
Graphics2D g2 = (Graphics2D) g;
Color color = Color.black;
Rectangle2D.Double a = new Rectangle2D.Double(250, 250, 10, 10);
Rectangle2D.Double fill = new Rectangle2D.Double(0, 0, 600, 400);
g2.setPaint(color);
g2.fill(fill);
while(isRunning){
g2.setPaint(Color.blue);
g2.fill(a);
try {
Thread.sleep(15L);
} catch (InterruptedException e) {
System.out.println("Interrupted!");
e.printStackTrace();
}
g2.setPaint(Color.black);
g2.fill(a);
a.setRect(x, y, 10, 10);
}
}
/**
* #param args
*/
public static void main(String[] args) {
JFrame jframe = new JFrame("Test");
jframe.setVisible(true);
jframe.setBounds(250, 250, 600, 400);
jframe.setResizable(false);
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JApplet applet = new MainClass();
jframe.getContentPane().add("Center", applet);
while(isRunning){
moveBall();
try {
Thread.sleep(15L);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Interrupted.");
}
}
}
}
[Edit]I forgot to mention that when I exported it into an executable JAR file and then ran it, I had to open Task Manager, which then told me it was not responding, in order to close it.
Is there anyway to re-write this so that it can close?
I think you're not listening the close event. Try with this:
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent evt) {
isRunnig = false;
}
}
and
jframe.addWindowListener(new WindowEventHandler());
Thread.sleep and main loop in Swing EDT are bad idea.
Use javax.swing.Timer.
Related
I have created a game similar to snake in which the user is first prompted with a jpanel asking which difficulty they want, and whatever JButton they pick influences the size of the map as well as the delay between the snake movements. I have the map size working just fine, but the delay variable never seems to change. I suspect it has something to do with the way the timer is being casted, but I have no idea how to fix it. I am also wondering how when the program is first ran it seems some of the variables don't update, but the second time it is ran all of them are updated. Here is my class with the original variables and collision detection:
import java.util.Random;
import javax.swing.JLabel;
public class GameEngine extends JPanel implements ActionListener{
//creates the size of the panel as well as creating the resolution for all objects, including the players and food.
static final int sWidth = 600;
static final int sHeight = 600;
public static int size = 24;
static int objectSize = (sHeight*sWidth) / size;
public static int delay = 100;
final int playerX[] = new int[objectSize];
final int playerY[] = new int[objectSize];
int bodySize = 4;
int score = 0;
int appleX;
int appleY;
char direction = 'D';
boolean started = false;
Random random;
Timer timer;
boolean easy;
JLabel score1;
public static String difficulty;
GameEngine(){
random = new Random();
this.setPreferredSize(new Dimension(sWidth,sHeight));
this.setBackground(Color.black);
this.setFocusable(true);
this.addKeyListener(new UserMovement());
gameStart();
}
public void gameStart() {
newApple();
started = true;
timer = new Timer(delay,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void drawHead(Graphics g) {
g.setColor(new Color(100,252,0));
g.fillRect(playerX[0], playerY[0], size, size);
}
public void draw(Graphics g) {
if(started) {
//draws the apples
g.setColor(Color.red);
g.fillOval(appleX, appleY, size, size);
for (int i = 0; i < bodySize; i++) {
if(i == 0) {
drawHead(g);
}
else {
g.setColor(new Color(60,180,0));
g.fillRect(playerX[i], playerY[i], size, size);
}
}
g.setColor(Color.white);
g.setFont(new Font("Bold", Font.BOLD, 20));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: " + score,(sWidth - metrics.stringWidth("Score: " + score))/2,g.getFont().getSize());
}
}
public void newApple(){
appleX = random.nextInt((int)(sWidth/size))*size;
appleY = random.nextInt((int)(sHeight/size))*size;
}
//moves the player by using and modifying their coordinates
public void move() {
for (int i = bodySize; i > 0; i--) {
playerX[i] = playerX[i-1];
playerY[i] = playerY[i-1];
}
switch(direction) {
case 'W':
playerY[0] = playerY[0] - size;
break;
case 'S':
playerY[0] = playerY[0] + size;
break;
case 'A':
playerX[0] = playerX[0] - size;
break;
case 'D':
playerX[0] = playerX[0] + size;
break;
}
}
public void checkFood() {
if(playerX[0] == appleX && playerY[0] == appleY)
{
bodySize++;
score++;
newApple();
}
}
public void checkCol() {
//checks for head collision with the body
for(int i = bodySize; i > 0; i--) {
if((playerX[0] == playerX[i]) && (playerY[0] == playerY[i])) {
started = false;
}
}
//checks if head touches any of the walls of the program
if(playerX[0] < 0) {
started = false;
}
if(playerX[0] > sWidth) {
started = false;
}
if(playerY[0] < 0) {
started = false;
}
if(playerY[0] > sHeight) {
started = false;
}
if(started != true) {
timer.stop();
}
}
public void actionPerformed(ActionEvent e){
if(started == true) {
move();
checkFood();
checkCol();
}
repaint();
}
public class UserMovement extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'D') {
direction = 'A';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'A') {
direction = 'D';
}
break;
case KeyEvent.VK_UP:
if(direction != 'S') {
direction = 'W';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'W') {
direction = 'S';
}
break;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
}
and here is the code calling and changing the delay and size variables:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class StartMenu extends JPanel {
StartMenu()
{
JButton easy = new JButton();
JButton hard = new JButton();
this.setPreferredSize(new Dimension(350,240));
this.setLayout(null);
this.setBackground(Color.black);
this.setFocusable(true);
easy.setBounds(75,40,200,40);
hard.setBounds(75,120,200,40);
this.add(easy);
this.add(hard);
easy.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
new SnakeStart();
GameEngine.size = 48;
GameEngine.delay = 140;
}
});
hard.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
setVisible(false);
new SnakeStart();
GameEngine.size = 24;
GameEngine.delay = 70;
}
});
}
}
I assume your GameEngine instance is created before the StartMenu action listeners are executed. If that assumption is correct, that means that GameEngine.timer with the default value of delay is created in the GameEngine constructor and is not updated after the delay is changed.
You need to make sure that you explicitly update your timer with the new delay value after StartMenu actions are called.
I have just started to learn Java, so excuse my messy code. Looking all over the internet, I have not found a solution to this question yet. This is the game pong. I have to padels that I am controlling ith the keys, 'w', 's', up, and down. When I draw the panels in my graphics section, I use the padelY for Y1 and use padelY + padelLength(A constant) for Y2. I cannot seem to understand why when I rut the program the padels change size as I move them up and down. Also, the padel on the right is named panel1, when I draw the padel I use the screen size - the padel spacing for X1 yet the padel appears to be stuck on the side.
I would really appreciate any advice that anyone could give on those issues or how to clean up my code in general!
Thanks!
package Pong;
//Import Libraries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
#SuppressWarnings("serial")
public class Pong extends JPanel implements KeyListener{
int padel1y = 150;
int padel2y = 150;
static final int padelLength = 100;
int padelWidth = 10;
int padelSpeed = 2;
int padel2Speed = 0;
int padel1Speed = 0;
int ballX = BOX_WIDTH/2;
int ballY= BOX_HEIGHT/2;
int ballXSpeed = 2;
int ballYSpeed = 1;
int ballRadius = 10;
int ballCount = 0;
public final static int ballSpeedIncrease = 500;
public final static int BOX_WIDTH = 600;
public final static int BOX_HEIGHT = 600;
public final static int UPDATE_RATE = 100;
public final static int padelSpace = 10;
public Pong() {
setPreferredSize(new Dimension(BOX_WIDTH,BOX_HEIGHT));
Thread gameThread = new Thread() {
public void run(){
while(true){
ballCount = ballCount + 1;
if(ballCount%ballSpeedIncrease == 0){
if(ballXSpeed < 0){
ballXSpeed = ballXSpeed - 1;
}
if(ballYSpeed < 0){
ballYSpeed = ballYSpeed - 1;
}
if(ballXSpeed > 0){
ballXSpeed++;
}
if(ballYSpeed > 0){
ballYSpeed++;
}
}
if(ballX-ballRadius <= 10+padelWidth){
if(ballY<padel2y || ballY>padel2y+padelLength){
System.exit(0);
}
else{
ballXSpeed = -ballXSpeed;
}
}
else if(ballX+ballRadius >= 590-padelWidth){
if(ballY<padel1y || ballY>padel1y+padelLength){
System.exit(0);
}
else{
ballXSpeed = -ballXSpeed;
}
}
if(ballY-ballRadius <= 0){
ballYSpeed = -ballYSpeed;
}
else if(ballY+ballRadius >= BOX_HEIGHT){
ballYSpeed = -ballYSpeed;
}
padel1y = padel1y +padel1Speed;
padel2y = padel2y +padel2Speed;
ballX = ballX + ballXSpeed;
ballY = ballY+ ballYSpeed;
repaint();
try {
Thread.sleep(1000 / UPDATE_RATE);
}
catch (InterruptedException ex) {}
}
}
};
gameThread.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.white);
g.fillRect(0,0,BOX_WIDTH,BOX_HEIGHT);
g.setColor(Color.blue);
g.fillRect(padelSpace,padel2y,padelSpace + padelWidth,padel2y+padelLength);
g.fillRect(BOX_WIDTH-padelSpace,padel1y,BOX_WIDTH-padelSpace-padelWidth,padel1y+padelLength);
g.setColor(Color.green);
g.fillOval(ballX, ballY, ballRadius*2, ballRadius*2);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//Create Frame
JFrame frame = new JFrame("PONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONGPONG");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Pong pong = new Pong();
frame.setContentPane(pong);
frame.setSize(BOX_WIDTH,BOX_HEIGHT);
frame.pack();
frame.addKeyListener(pong);
frame.setVisible(true);
}
});
}
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP){
padel1Speed = -padelSpeed;
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
padel1Speed = padelSpeed;
}
else if(e.getKeyCode() == KeyEvent.VK_W){
padel2Speed = -padelSpeed;
}
else if(e.getKeyCode() == KeyEvent.VK_S){
padel2Speed = padelSpeed;
}
}
#Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
padel1Speed = 0;
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN){
padel1Speed = 0;
}
else if(e.getKeyCode() == KeyEvent.VK_W){
padel2Speed = 0;
}
else if(e.getKeyCode() == KeyEvent.VK_S){
padel2Speed = 0;
}
}
#Override
public void keyTyped(KeyEvent e) {}
}
See this for documentation on how to use the fillRect() method: https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html#fillRect(int,%20int,%20int,%20int)
The arguments are: x position, y position, width and height.
You use it like this: g.fillRect(padelSpace,padel2y,padelSpace + padelWidth,padel2y+padelLength);
The second and third arguments are wrong. You should only be passing the width and height. Like this: g.fillRect(padelSpace, padel2y, padelWidth, padelLength);
More generally, when something is going wrong (drawing the paddle) read the documentation on the methods you use to do that.
I am having an issue with the command super.paintComponents(g); when updating a JFrame. The issue I am having is that the image I am loading is blinking while the code is running. I am pretty sure that the code is double buffering and have not found any helpful resource online to solve this issue. This is my first question so please tolerate any formatting errors.
Here is my entire code (snippets below):
public class GAME extends JFrame implements KeyListener, MouseMotionListener {
int mouseX, mouseY;
public static ArrayList<Images> images = new ArrayList<Images>();
public static String lastKeyPressed = null;
public GAME() {
this.addMouseMotionListener(this);
this.addKeyListener(this);
}
public void mouseDragged(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
public void mouseMoved(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == e.VK_LEFT) {
lastKeyPressed = "LEFT";
} else if (e.getKeyCode() == e.VK_RIGHT) {
lastKeyPressed = "RIGHT";
} else if (e.getKeyCode() == e.VK_UP) {
lastKeyPressed = "UP";
} else if (e.getKeyCode() == e.VK_DOWN) {
lastKeyPressed = "DOWN";
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
#Override
public void paint(Graphics g) {
super.paintComponents(g);
for (int i = 0; i < images.size(); i++) {
g.drawImage(images.get(i).img, images.get(i).xpos, images.get(i).ypos, null);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
GAME frame = new GAME();
Dimension dim = new Dimension(800, 600);
frame.setPreferredSize(dim);
frame.setSize(dim);
frame.setResizable(false);
frame.setTitle("GAME");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Images test = new Images("unnamed.png");
images.add(test);
while (true) {
if (lastKeyPressed == "LEFT") {
test.xpos -= 5;
lastKeyPressed = null;
} else if (lastKeyPressed == "RIGHT") {
test.xpos += 5;
lastKeyPressed = null;
} else if (lastKeyPressed == "UP") {
test.ypos -= 5;
lastKeyPressed = null;
} else if (lastKeyPressed == "DOWN") {
test.ypos += 5;
lastKeyPressed = null;
}
frame.repaint();
Thread.sleep(100);
}
}
}
Here is the images class:
public class Images {
String name;
BufferedImage img;
int xpos;
int ypos;
public Images (String Name) throws IOException{
name = Name;
xpos = 40;
ypos = 90;
System.out.println(name);
System.out.println("PATH: " + GAME.class.getResource(name));
URL file = getClass().getClassLoader().getResource(name);
img = ImageIO.read(file);
}
}
What you probably only want to see is the following:
My paint method:
#Override
public void paint(Graphics g) {
super.paintComponents(g);
for (int i = 0; i < images.size(); i++) {
g.drawImage(images.get(i).img, images.get(i).xpos, images.get(i).ypos, null);
}
}
And the block of code in the main class that is running the game:
Images test = new Images("unnamed.png");
images.add(test);
while (true) {
if (lastKeyPressed == "LEFT") {
test.xpos -= 5;
lastKeyPressed = null;
} else if (lastKeyPressed == "RIGHT") {
test.xpos += 5;
lastKeyPressed = null;
} else if (lastKeyPressed == "UP") {
test.ypos -= 5;
lastKeyPressed = null;
} else if (lastKeyPressed == "DOWN") {
test.ypos += 5;
lastKeyPressed = null;
}
frame.repaint();
Thread.sleep(100);
}
(I added the Thread.sleep because it seemed to decrease the rate at which the blinking occurred)
Here is a gif of what is happening (I just used the first Google result for 'test' for the image):
http://i.imgur.com/WjLCSvu.gif?1
I appreciate any help and general suggestions to better my code. Thank you.
Don't override paint of top level containers like JFrame there aren't double buffered, instead, use a JPanel and override its paintComponent method. JPanel is double buffered by default.
Then, add the panel to what ever container you want
Don't forget to call it's super method (super.paintComponent) before you do any custom painting.
Take a closer look at Painting in AWT and Swing and Performing Custom Painting for more details about how painting works in Swing
This is just one reason why you shouldn't (extend from JFrame and) override paint of top level containers, take a look at
How can I set in the midst?
Graphics rendering in title bar
Java JFrame .setSize(x, y) not working?
How to get the EXACT middle of a screen, even when re-sized
for some more
I am making a JFrame holding several images that refresh using repaint(). The problem, however, was that the more images I added (or as the area that was being rendered increased) the framerate drastically decreased.
I was initially attempting to reduce the lag that Swing's unpredictable Timer experiences, but was unsuccessful. This time, I tried to call
repaint()
every 10 milliseconds based on system time. (To bypass the timer, desktop.screenPaint.drawWindow(); is called instead of repaint())
while(true)
{
long starttime = System.currentTimeMillis();
while(System.currentTimeMillis()-starttime < 10)
{
}
desktop.screenPaint.drawWindow();
desktop2.screenPaint.drawWindow();
}
Each "desktop" is just one of the draggable windows that you see if you run the code below. I noticed that when only "desktop" is added to "frame," there is no flickering. However, when "desktop2" is also added, flickering does not go away until the time until each refresh is set to 20 or more milliseconds. It is extremely strange, because when I was still using the timer, even thought the wait was set to 10 milliseconds, the framerate would lower to a frame every 20 milliseconds! I tested a little and noticed a trend: you will get flickering until the wait time to the amount of time that the 10 millisecond timer lagged behind. My question: Why is this happening? And is there any way to prevent the flickering, other than going back to the timer?
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.SwingUtilities.*;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
import java.io.File;
import java.io.IOException;
public class Display extends JPanel
{
public static int width, height;
public static JFrame frame = new JFrame("");
private static int rh = 10;
public static Display desktop = new Display();
public static Display desktop2 = new Display();
public static void main(String[] args)
{
Dimension screen = new Dimension();
screen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
width = (int)screen.getWidth();
height = (int)screen.getHeight();
frame.setLayout(null);
frame.setLocation(0, 0);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
desktop.setBounds(0, 0, 620, 500+rh);
desktop2.setBounds(1000, 200, 620, 500+rh);
frame.add(desktop);
frame.add(desktop2);
frame.setUndecorated(true);
frame.setSize(width, height);
frame.setVisible(true);
while(true)
{
long starttime = System.currentTimeMillis();
while(System.currentTimeMillis()-starttime < 10)
{
}
desktop.screenPaint.drawWindow();
//desktop2.screenPaint.drawWindow();
}
}
private BufferedImage image;
private Graphics2D g;
public Listener screenPaint = new Listener();
private Display identify;
public Display()
{
identify = this;
image = new BufferedImage(620, 500+rh, BufferedImage.TYPE_INT_RGB);
g = (Graphics2D)image.getGraphics();
Timer timer = new Timer(1, screenPaint);
timer.start();
addMouseListener(new mMouse());
addMouseWheelListener(new wWheel());
setFocusable(true);
}
private BufferedImage toCompatibleImage(BufferedImage image)
{
GraphicsConfiguration gfx_config = GraphicsEnvironment.
getLocalGraphicsEnvironment().getDefaultScreenDevice().
getDefaultConfiguration();
if (image.getColorModel().equals(gfx_config.getColorModel()))
return image;
BufferedImage new_image = gfx_config.createCompatibleImage(
image.getWidth(), image.getHeight(), image.getTransparency());
}
public void paint(Graphics view)
{
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
view.drawImage(toCompatibleImage(image), 0, 0, 620, 500+rh, null);
view.dispose();
}
private class Listener implements ActionListener
{
int y = 0;
int wy = 0;
int b = 500;
int c = 1500;
int iy = (int)(wy/(c/(double)b));
int a = -1;
int i = -1;
int j = -1;
boolean d = false;
boolean u = false;
int f = 0;
public void moveY(int sy)
{
f += sy;
}
public void actionPerformed(ActionEvent e)
{
//drawWindow();
}
public void drawWindow()
{
int lx = (int)(identify.getLocation().getX());
int ly = (int)(identify.getLocation().getY());
g.setColor(Color.white);
g.fillRect(0, 0, 620, 500+rh);
g.drawImage(new ImageIcon("image.png").getImage(), 0, wy+rh, 610, c, null);
if(c > b)
{
if(d || Mouse.withinRect(610+lx, (int)(-wy/(c/(double)b))+rh+ly, 10, (int)Math.ceil(Math.pow(b, 2)/(double)c)))
{
if(Mouse.pressLeft())
{
if(!d)d = true;
if(a == -1)a = Mouse.y()-(int)(-wy/(c/(double)b));
y = (int)((Mouse.y()-a)*(c/(double)b));
f = y;
g.setColor(Color.black);
}
else
{
if(d)d = false;
if(a != -1)a = -1;
g.setColor(new Color(60, 60, 60));
}
}
else
{
g.setColor(Color.gray);
if(a != -1)a = -1;
}
if(y == f){}
else if(y < f)
{
y += (int)((f-y)*0.1);
if(y < f)y++;
}
else
{
y -= (int)((y-f)*0.1);
if(y > f)y--;
}
if(y < 0)
{
y = 0;
f = 0;
}
else if(y > c-b)
{
y = c-b;
f = y;
}
wy = -y;
if(u || Mouse.withinRect(lx, ly, 620, 10))
{
if(Mouse.pressLeft())
{
if(!u)u = true;
if(i == -1)i = Mouse.x()-lx;
if(j == -1)j = Mouse.y()-ly;
identify.setLocation(Mouse.x()-i, Mouse.y()-j);
}
else
{
if(u)u = false;
if(i != -1)i = -1;
if(j != -1)j = -1;
}
}
else
{
if(u)u = false;
if(i != -1)i = -1;
if(j != -1)j = -1;
}
int scrollBarLength = (int)Math.ceil(Math.pow(b, 2)/(double)c);
g.fillRect(610, (int)(-wy/(c/(double)b))+rh, 10, scrollBarLength);
}
else
{
g.setColor(new Color(200, 200, 200));
g.fillRect(610, rh, 10, b);
}
g.setColor(new Color(50, 50, 50));
g.fillRect(0, 0, 620, rh);
if(identify == desktop)
repaint();
else if(false)
{}
}
}
}
public static boolean LMPress, LMRelease = false;
public static boolean LMRight, LMLeft = false;
private class mMouse extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
LMPress = true; LMRelease = false;
if(SwingUtilities.isRightMouseButton(e))
{
LMRight = true;
LMLeft = false;
}
else if(SwingUtilities.isLeftMouseButton(e))
{
LMLeft = true;
LMRight = false;
}
}
public void mouseReleased(MouseEvent e)
{
LMRelease = true; LMPress = false;
if(SwingUtilities.isRightMouseButton(e))
{
LMRight = true;
LMLeft = false;
}
else if(SwingUtilities.isLeftMouseButton(e))
{
LMLeft = true;
LMRight = false;
}
}
}
private class wWheel implements MouseWheelListener
{
public void mouseWheelMoved(MouseWheelEvent e)
{
int notches = e.getWheelRotation();
if (e.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL) {}
e.getScrollAmount();
screenPaint.moveY(e.getUnitsToScroll()*60); //desired pixel jump: 120
}
}
}
Mouse class:
import java.awt.*;
import java.awt.event.*;
public class Mouse {
public static int x() {
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
return (int) b.getX();
}
public static int y() {
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
return (int) b.getY();
}
public static boolean withinRect(int x, int y, int w, int h) {
if (x() >= x && x() < x + w && y() >= y && y() < y + h) return true;
else return false;
}
public static boolean press() {
return Display.LMPress;
}
public static boolean release() {
return Display.LMRelease;
}
public static boolean pressLeft() {
if (Display.LMPress && Display.LMLeft)
return true;
else return false;
}
public static boolean releaseLeft() {
if (Display.LMRelease && Display.LMLeft)
return true;
else return false;
}
public static boolean pressRight() {
if (Display.LMPress && Display.LMRight)
return true;
else return false;
}
public static boolean releaseRight() {
if (Display.LMRelease && Display.LMRight)
return true;
else return false;
}
}
Updating the view at 1 kHz is unrealistic; instead, consider the alternatives cited here. See this AnimationTest for an example of self-timing to determine your animation budget.
Addendum: The while(true) loop at the top is running at 100 Hz.
The available resolution of System.currentTimeMillis() may vary by platform.
Addendum: I am reopening this question because I was not able to fix it. Any more help?
Absent a Minimal, Complete, Tested and Readable Example, it's hard to say. You appear to be overriding paint(); was noted in Painting in AWT and Swing: The Paint Methods, "Swing programs should override paintComponent()." Moreover, you need to invoke super.paintComponent(), as shown here, to avoid visual artifacts.
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
}