marco1991
21-04-2012, 21:16
salve raga,
ho scritto poche righe di codice che creano una semplice JFrame nella quale cè un JButton.
Quando si clicca il bottone, questo si sposta a random in giro per la finestra..
per fare in modo che il bottone non esca dalla finestra stessa ho mesos in random così:
nuova altitudine bottone = rand.nextInt(altezza finestra - altezza bottone);
nuova latitudine bottone = rand.nextInt(larghezza finestra - larghezza bottone);
però purtroppo facendo così il bottoe sfora cmq.. il codice è questo:
package bottonechescappa;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.*;
/**
*
* @author francesco
*/
public class Click implements ActionListener{
Random rand;
JPanel contenitore;
JButton button;
public Click(JPanel contenitore, JButton button){
rand = new Random(System.currentTimeMillis());
this.contenitore = contenitore;
this.button = button;
}
public void actionPerformed(ActionEvent e) {
button.setLocation(rand.nextInt(Main.dimFinestra.width - button.getWidth()), rand.nextInt(Main.dimFinestra.height - button.getHeight() ));
}
}
class ButtonPanel extends JPanel{
ButtonPanel(){ super();
JButton button = new JButton("click here!");
this.setSize(400, 400);
this.add(button);
Click clicklist = new Click(this, button);
button.addActionListener(clicklist);
}
}
ho scritto poche righe di codice che creano una semplice JFrame nella quale cè un JButton.
Quando si clicca il bottone, questo si sposta a random in giro per la finestra..
per fare in modo che il bottone non esca dalla finestra stessa ho mesos in random così:
nuova altitudine bottone = rand.nextInt(altezza finestra - altezza bottone);
nuova latitudine bottone = rand.nextInt(larghezza finestra - larghezza bottone);
però purtroppo facendo così il bottoe sfora cmq.. il codice è questo:
package bottonechescappa;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.*;
/**
*
* @author francesco
*/
public class Click implements ActionListener{
Random rand;
JPanel contenitore;
JButton button;
public Click(JPanel contenitore, JButton button){
rand = new Random(System.currentTimeMillis());
this.contenitore = contenitore;
this.button = button;
}
public void actionPerformed(ActionEvent e) {
button.setLocation(rand.nextInt(Main.dimFinestra.width - button.getWidth()), rand.nextInt(Main.dimFinestra.height - button.getHeight() ));
}
}
class ButtonPanel extends JPanel{
ButtonPanel(){ super();
JButton button = new JButton("click here!");
this.setSize(400, 400);
this.add(button);
Click clicklist = new Click(this, button);
button.addActionListener(clicklist);
}
}