简体   繁体   中英

Java Swing + Timer? Moving a line across JPanel

What I'm trying to do is simple. I have a JLayeredPane with two panels inside of it. Panel 2 (higher Z index) has a transparent background and only displays a Line2D element that goes from Y = 0 to Y = max. I need the X value to increment every so many milliseconds, and then redraw the line. I have everything set up to do so, except I can't figure out how to do the bar movement via timing.

I've done some research and every time I saw mentions of the timer class (Which I feel would be able to accomplish what I'm trying to do) people recommend not using it. I can't figure out an alternative to using the timer class in order to slide my bar across the screen.

Hope this code helps you. It does exactly what you want.

import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
import java.awt.EventQueue;
import javax.swing.JFrame;

public class FloorPlaner extends JFrame {
     public int x=0;

     public FloorPlaner(){ 
          super("FloorPlaner");

          requestFocus(); 

          setContentPane(new DrawingPane());

          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

          setSize(400, 400);

          setResizable(true); 

          setVisible(true); 

          while (true) { 
              x++;
              repaint();
              try {
              Thread.sleep(40); //25 FPS
              } catch(InterruptedException bug) {
              Thread.currentThread().interrupt();
              System.out.println(bug);
              }
          }
     }


     class DrawingPane extends JPanel { //Where you actually draw on
        public void paintComponent(Graphics g) { //Drawing method
           g.drawLine(x,0,x,400);
        }   
     }
     public static void main(String args[]) {
            new FloorPlaner(); //Start it
     }
}

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