Se ti è stato richiesto allora devi per forza farlo.....
Anche se non è corretta inquanto utilizzando un thread estreno l'EDT non sa come gestirlo...
Bando alle ciance e implementiamo il metodo con un thread...
codice:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class Test extends JFrame implements ActionListener
{
private final JTextArea jTextArea1;
public Test()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
jTextArea1 = new JTextArea();
JScrollPane jScrollPane = new JScrollPane(jTextArea1);
this.add(jScrollPane);
JButton actionButton = new JButton("START");
actionButton.addActionListener(this);
this.add(actionButton, BorderLayout.NORTH);
this.pack();
}
@Override
public void actionPerformed(ActionEvent e)
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
jTextArea1.append("ciao \n");
}
}
});
thread.start();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
Test test = new Test();
test.setVisible(true);
}
});
}
}
il codice importante è questo:
codice:
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
while (true)
{
jTextArea1.append("ciao \n");
}
}
});
thread.start();
Come vedi vado a creare un nuovo Thread a cui passo un oggetto Runnable che implementa la logica applicativa. Ovviamente qui io ho usato un inner class ma puoi benissimo (Anzi consiglio) di creare una classe a parte che implementa runnable....