Un banale esempio funzionante:
codice:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MioRettangolo extends JFrame implements ActionListener {
private class MioPannello extends JPanel {
private int x;
private int y;
@Override
public void paintComponent(Graphics g) {
g.setColor( Color.BLUE );
g.fillRect(x, y, 50, 50);
}
public void sposta() {
if (x > 550) {
x = -1;
y = -1;
}
x++;
y++;
}
}
private MioPannello pannello;
private Timer timer;
public MioRettangolo() {
Container c = getContentPane();
c.setLayout( new BorderLayout() );
pannello = new MioPannello();
c.add(pannello, BorderLayout.CENTER);
setTitle("Pannello spostante");
setSize(800, 600);
setDefaultCloseOperation( DO_NOTHING_ON_CLOSE );
addWindowListener( new WindowAdapter() {
@Override
public void windowClosing(WindowEvent we) {
chiudiApplicazione();
}
});
setLocationRelativeTo( null );
setVisible( true );
timer = new Timer(200, this);
timer.start();
}
private void chiudiApplicazione() {
timer.stop();
dispose();
}
@Override
public void actionPerformed(ActionEvent ae) {
pannello.sposta();
repaint();
}
public static void main(String[] args) {
MioRettangolo mr = new MioRettangolo();
}
}
Ciao.