简体   繁体   中英

JLabel isn't moving

I'm attempting to make a program that moves a label down and to the right of the frame but nothing is working, the while loop is being triggered so the code is running but the label wont move. Sorry I'm a beginner and don't really understand what's going on.

The code also uses the Stopwatch class shown below the animation code.

animation

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class animation {

private JFrame frame;

boolean isMoving = false;
int labelX = 0;
int labelY = 0;
int x, y;
private final JButton button = new JButton("Start");
JLabel lblO = new JLabel("O");

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                animation window = new animation();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public animation() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
     x = frame.getWidth();
     y = frame.getHeight();

    lblO.setBounds(0, 0, 15, 15);
    frame.getContentPane().add(lblO);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            button.setText("End");
            if(isMoving){

                movetheball();
            }
            else{
                isMoving = true;
            }
            }
    });
    button.setBounds(168, 219, 84, 31);
    frame.getContentPane().add(button);
    }

public void movetheball(){
    StopWatch tim = new StopWatch();
    tim.start();
    while(isMoving){
        long time = tim.getElapsedtime();
        if(time>1){

            System.out.println("The Timer is Working");
            labelX+= 150;
            labelY += 150;
            lblO.setBounds(labelX,labelY,15,15);
            }
    }
}
}

Stopwatch

    public class StopWatch {
private long elapsedTime;
private long startTime;
private boolean isRunning;

public StopWatch(){

}

public void start(){
    isRunning = true;
    startTime = System.currentTimeMillis();
    }

public void stop(){
    isRunning = false;

}

public long getElapsedtime(){
    if(isRunning){
        long  endTime =System.currentTimeMillis();
        return elapsedTime + endTime - startTime;

    }
    else{
        return elapsedTime;
    }
}
public void reset(){
    elapsedTime = 0;
    isRunning = false;
}
}

You have got a couple of issues in your code:

1) You need to click your button twice to be able to kick start the animation. Rework your logic in actionPerformed code.

2) You are moving your label too far on first move. Use increment of 1 instead of 150.

3) Your animation is in event dispatch thread and it freezes the GUI. Move it into separate thread and update JLabel in event dispatch thread.

Here is working code:

    public static class animation {

private JFrame frame;

boolean isMoving = false;
int labelX = 0;
int labelY = 0;
int x, y;
private final JButton button = new JButton("Start");
JLabel lblO = new JLabel("O");
/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                animation window = new animation();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public animation() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
     x = frame.getWidth();
     y = frame.getHeight();

    lblO.setBounds(0, 0, 15, 15);
    frame.getContentPane().add(lblO);
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            button.setText("End");
            if(isMoving){

                new Thread( () -> movetheball() ).start();
            }
            else{
                isMoving = true;
            }
            }

    });
    button.setBounds(168, 219, 84, 31);
    frame.getContentPane().add(button);



    }

public void movetheball(){
    StopWatch tim = new StopWatch();
    tim.start();
    while(isMoving){

        long time = tim.getElapsedtime();
        if(time>1){

            System.out.println("The Timer is Working");
            labelX+= 1;
            labelY += 1;

            EventQueue.invokeLater( () -> lblO.setBounds(labelX,labelY,15,15) );

            try {
                Thread.sleep( 100 );
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
    }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM