una tiempo segundos poner método metodo imagen hora especifica ejemplos ejecutar cronometro como cierto cambiar cada alarma java random timer jpanel

java - tiempo - poner una imagen en un label netbeans



¿Cómo puedo hacer que la imagen aparezca aleatoriamente cada x segundos en Java usando el temporizador? (2)

Estoy trabajando en un juego en el que necesito ''golpear'' a un ratón / rata, desaparecerá y obtendrás 1 punto. Lo hice aparecer al azar cada vez que inicié la aplicación, pero quiero que la imagen se dibuje al azar cada x segundos usando Timer () o algo así.

Mi código para la pantalla del juego se ve así:

import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JTextField; public class Gamevenster extends JPanel implements Runnable { public String Gamestatus = "active"; private Thread thread; //public Main game; public int random(int min, int max) { int range = (max - min) + 1; return (int)(Math.random() * range) + min; } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(achtergrond, 0, 0, this.getWidth(), this.getHeight(), null); //g.drawImage(muisje, 10, 10, null); g.drawImage(muisje, random(0, this.getWidth()), random(0, this.getHeight()), null); } private static final long serialVersionUID = 1L; Image achtergrond, muisje; JTextField invoer; JButton raden; JButton menu; Gamevenster() { setLayout(null); ImageIcon icon = new ImageIcon(this.getClass().getResource("assets/achtergrondspel.png")); achtergrond = icon.getImage(); ImageIcon icon2 = new ImageIcon(this.getClass().getResource("assets/muisje.png")); muisje = icon2.getImage(); //Get the default toolkit Toolkit toolkit = Toolkit.getDefaultToolkit(); //Load an image for the cursor Image image = toolkit.getImage("src/assets/hand.png"); //Create the hotspot for the cursor Point hotSpot = new Point(0,0); //Create the custom cursor Cursor cursor = toolkit.createCustomCursor(image, hotSpot, "Hand"); //Use the custom cursor setCursor(cursor); // setLayout( null ); // Invoer feld invoer = new JTextField(10); invoer.setLayout(null); invoer.setBounds(150, 474, 290, 60); // Verander positie onder aan scherm is int 1 // Button voor raden raden = new JButton("Raden"); raden.setLayout(null); raden.setBounds(10, 474, 130, 60); raden.setFont(new Font("Dialog", 1, 20)); raden.setForeground(Color.white); raden.setBackground(new Color(46, 204, 113)); raden.setPreferredSize(new Dimension(130, 60)); // Menu knop menu = new JButton("Menu"); menu.setLayout(null); menu.setBounds(450, 474, 130, 60); menu.setFont(new Font("Dialog", 1, 20)); menu.setForeground(Color.white); menu.setBackground(new Color(46, 204, 113)); menu.setPreferredSize(new Dimension(130, 60)); // Toevoegen aan screen add(invoer); //add(raden); add(menu); menu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String i = invoer.getText(); System.out.println("Er is gedrukt! " + i); } }); } public void start(){ thread = new Thread(this,"spelloop"); thread.start(); } public void run() { // TODO Auto-generated method stub while(Gamestatus=="active"){ System.out.println("Gameloop werkt"); } } }

como puedes ver, estoy usando g.drawImage (muisje, random (0, this.getWidth ()), random (0, this.getHeight ()), null);

Por lo tanto, agrega aleatoriamente la imagen al inicio.

¿Cómo puedo usar un temporizador para hacer esto cada x segundos cuando la aplicación está abierta?


Bueno, yo también soy un principiante. Entonces, si te equivoco, lo siento de antemano. Esa es mi primera respuesta. Lo que estás buscando es probablemente esto
System.currentTimeMillis();
esto dará la hora actual como milisecs. Por lo tanto, es probable que desee utilizar otro flotador para calcular el tiempo transcurrido y le nombremos deltaTime. Puede encontrar deltaTime por deltaTime=System.currentTimeMillis(); use esto antes mientras el bucle en el método de ejecución. Luego, dentro del ciclo, si System.currentTimeMillis()-deltaTime es mayor que x número (milisegundos), genere una rata. Y restablecer deltaTime.

Y veo que no has declarado ax, y posición entero para almacenar las ratas x y y ubicación. Así que declara 2 variables globales para xey de ratas. si las ratas múltiples que x y y int deben ser matrices con espacio suficiente para mantener todas sus posiciones de ratas.

Haz un método para que cada vez que aparezca una rata, xey de la ubicación de la rata obtenga un int aleatorio. De hecho lo descubriste en la sección de gráficos. Pero la función aleatoria no debería estar allí. En lugar de la función aleatoria xey los enteros deberían estar allí. En su código, aleatorizará la ubicación de la rata cada vez que actualice los gráficos. No, eso no es lo que quieres (probablemente).

Una cosa más, su código en realidad no funcionará sin el método de actualización llamado. Deberías poner update(); al final de tu ciclo while

Lo siento si estoy equivocado o no lo suficientemente claro. Solo soy un principiante interesado en los mismos temas antes.


"¿Cómo puedo usar un temporizador para hacer esto cada x segundos cuando se abre la aplicación?"

Echa un vistazo a este ejemplo. Reuní Imágenes de internet, pero puedes hacer lo mismo usando archivos de imágenes. Lo que hice fue utilizar una matriz de URL y BufferedImage y obtuve un índice aleatorio de 500 milisegundos y volver a repaint() el panel

Nota: Si va a utilizar archivos de imagen, también puede consultar esta respuesta .

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.Timer; public class TestImageRotate { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { JFrame frame = new JFrame("Image Timer"); frame.add(new ImagePanel()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private static class ImagePanel extends JPanel { URL[] urls; BufferedImage[] images; Random rand = new Random(); public ImagePanel() { urls = new URL[5]; try { urls[0] = new URL("http://www.atomicframework.com/assetsY/img/_chicklet.png"); urls[1] = new URL("http://www.iconsdb.com/icons/download/orange/-256.png"); urls[2] = new URL("http://img.1mobile.com/market/screenshot/50/com.dd./0.png"); urls[3] = new URL("http://www.iconsdb.com/icons/download/orange/-4-512.png"); urls[4] = new URL("http://www.iconsdb.com/icons/preview/light-gray/-xxl.png"); images = new BufferedImage[5]; images[0] = ImageIO.read(urls[0]); images[1] = ImageIO.read(urls[1]); images[2] = ImageIO.read(urls[2]); images[3] = ImageIO.read(urls[3]); images[4] = ImageIO.read(urls[4]); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } setBackground(Color.BLACK); Timer timer = new Timer(500, new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { repaint(); } }); timer.start(); } private int random() { int index = rand.nextInt(5); return index; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage img = images[random()]; g.drawImage(img, 0, 0, 400, 400, 0, 0, img.getWidth(), img.getHeight(), this); } @Override public Dimension getPreferredSize() { return new Dimension(400, 400); } } }

Observe el código del Timer . Esto es todo lo que hice

Timer timer = new Timer(500, new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { repaint(); } }); timer.start();

Y para .grawImage utilizo un índice aleatorio de la matriz de BufferedImages

@Override protected void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage img = images[random()]; g.drawImage(img, 0, 0, 400, 400, 0, 0, img.getWidth(), img.getHeight(), this); }

Ejemplo de ACTUALIZACIÓN . Cerré mi IDE por la noche. Demasiado perezoso para abrir, así que voy a pensar en esto a medida que avance. Si aún no lo haces, añadiré un ejemplo real mañana cuando me levante.

Básicamente, desea tener una variable global para las ubicaciones x e y de la imagen del mouse

int x = 0; int y = 0;

Cuando dibujas la imagen, quieres usar estas ubicaciones

g.drawImage(img, x, y, whatEverWidth, whatEverHeight, this);

En el temporizador, puedes modificar la xey al azar antes de pintar. Deje que use algo de lógica.

Supongamos que el ancho de su pantalla es 500 y la altura de la pantalla es 500 y el ancho de la imagen del mouse es 100 y la altura de la imagen del mouse es 100

  • Entonces, la ubicación max x será 400 = ancho de la pantalla - ancho de la imagen del mouse
  • Y la ubicación max y será 400 = altura de la pantalla - altura de la imagen del mouse

Entonces ahora tenemos nuestros rangos. Sabemos que la ubicación min x es 0 y la ubicación mínima es 0. Entonces queremos un número aleatorio de 0 a 400 para cada x e y. Entonces en el temporizador puedes hacer

Timer timer = new Timer(1000, new ActionListener(){ public void actionPerformed(ActionEvent e) { x = rand.nextInt(400) + 1; y = rand.nextInt(400) + 1; repaint(); } });

Esto volverá a pintar la imagen del mouse en una ubicación aleatoria cada vez que se llame a repintado.

ACTUALIZACIÓN 2

No sé qué más hay para explicar. Hice exactamente las cosas que señalé (con mi código original), simplemente agregué una y y las usé para dibujar la imagen, y obtuve una ubicación aleatoria en el timer . Funciona perfectamente bien para mí. No sé lo que estás haciendo mal.

import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Random; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.Timer; public class TestImageRotate { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { JFrame frame = new JFrame("Image Timer"); frame.add(new ImagePanel()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private static class ImagePanel extends JPanel { URL[] urls; BufferedImage[] images; Random rand = new Random(); private int x = 0; private int y = 0; public ImagePanel() { urls = new URL[5]; try { urls[0] = new URL("http://www.atomicframework.com/assetsY/img/_chicklet.png"); urls[1] = new URL("http://www.iconsdb.com/icons/download/orange/-256.png"); urls[2] = new URL("http://img.1mobile.com/market/screenshot/50/com.dd./0.png"); urls[3] = new URL("http://www.iconsdb.com/icons/download/orange/-4-512.png"); urls[4] = new URL("http://www.iconsdb.com/icons/preview/light-gray/-xxl.png"); images = new BufferedImage[5]; images[0] = ImageIO.read(urls[0]); images[1] = ImageIO.read(urls[1]); images[2] = ImageIO.read(urls[2]); images[3] = ImageIO.read(urls[3]); images[4] = ImageIO.read(urls[4]); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } setBackground(Color.BLACK); Timer timer = new Timer(500, new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { x = rand.nextInt(325); y = rand.nextInt(325); repaint(); } }); timer.start(); } private int random() { int index = rand.nextInt(5); return index; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); BufferedImage img = images[random()]; g.drawImage(img, x, y, 75, 75, this); } @Override public Dimension getPreferredSize() { return new Dimension(400, 400); } } }