Movimentar componentes em execução

1 resposta
gqferreira
Olá pessoal! Como movimentar componentes GUI em execução? Mais especificamente dentro de um laço para o movimento ser graduado. Tipo isso que tentei:
package testes;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.WindowConstants;

public class Teste extends javax.swing.JFrame {
	private JButton bt;

	public static void main(String[] args) {

		Teste inst = new Teste();
		inst.setLocationRelativeTo(null);
		inst.setVisible(true);
	}

	public Teste() {
		try {
			setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			getContentPane().setLayout(null);
			{
				bt = new JButton();
				getContentPane().add(bt, "Center");
				bt.setBounds(3, 25, 79, 203);

				bt.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try
						{
							for (int i = 0;i<315;i++)
							{
								Thread.sleep(3);
								bt.setLocation(i,25);
							}
						}
						catch(Exception ex){ex.printStackTrace();}
					}
				});
			}
			pack();
			setSize(400, 300);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

... mas não deu certo... a interface só é atualizada no final do laço. Já tentei repaint() e CIA....

Valeu gente!

1 Resposta

dstori

Crie uma nova Thread para resolver este problema:

public void actionPerformed(ActionEvent evt) {
						
						Thread x = new Thread() {
							
							public void run() {
								for (int i = 0; i < 315; i++) {
									try {
										Thread.sleep(3);
									} catch (InterruptedException e) {
										e.printStackTrace();
									}
									bt.setLocation(i, 25);
								}
							}
						};
						x.setName("buddy");
						x.start();
					}
Criado 8 de agosto de 2009
Ultima resposta 10 de ago. de 2009
Respostas 1
Participantes 2