我是JAVA的新手。 尝试一个简单的应用程序,一个线程。我有一个textarea框架。当我从一个类开始一个线程时,我想输出到textarea而不是控制台。 我无法在任何地方找到如何做到这一点。但它应该很简单??? 请帮忙。 以下是文件:
file 01/03 = MaFenetre.java
public class MaFenetre
{
public static void main (String args[])
{
Fenetre fen = new Fenetre() ;
fen.setVisible(true) ;
MyThread test = new MyThread (15) ;
test.start() ;
}
}
文件02/03 = Fenetre.java
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class Fenetre extends JFrame// implements ActionListener
{
private JTextArea zoneTexte;
// Constructeur
public Fenetre ()
{
setTitle ("Avec deux boutons") ;
setSize (700, 550) ;
Container contenu = getContentPane() ;
contenu.setLayout(new FlowLayout()) ;
zoneTexte=new JTextArea(5,20);
contenu.add(zoneTexte) ;
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void AddTxt(String txt)
{
this.zoneTexte.append(txt);
}
}
文件03/03:MyThread.java
public class MyThread extends Thread
{
private int nb ;
public MyThread (int nb)
{
this.nb = nb ;
}
public void run ()
{
try
{
for(int i=0 ; i<nb ; i++)
{
System.out.print ("test "+i+"\n");
sleep (500);
}
}
catch (InterruptedException e) {}
}
}
所以我只想: AddTxt(&#34; test&#34; + i +&#34; \ n&#34;); 代替 : System.out.print(&#34; test&#34; + i +&#34; \ n&#34;); 但是,当然,它不起作用。 问候。
答案 0 :(得分:2)
将Fenetre
对象传递给线程,以便您可以在run方法中访问该对象。
在run方法中,我们假设fe
是Fenetre
的对象。
public void run ()
{
try
{
for(int i=0 ; i<nb ; i++)
{
System.out.print ("test "+i+"\n");
SwingUtilities.invokeLater(
new Runnable()
{
fe.AddTxt("test "+i+"\n");
});sleep (500);
}
}
catch (InterruptedException e) {}
}
答案 1 :(得分:1)
所以我只想:AddTxt(“test”+ i +“\ n”);而不是:System.out.print(“test”+ i +“\ n”);但是,当然,它不起作用。问候。
它无法工作,因为你的Thread-class不知道你的Frame-class。
public class MyThread extends Thread
{
private int nb ;
private Fenetre fen;
public void setFenetre(final Fenetre fen) {
this.fen = fen;
}
public MyThread (int nb)
{
this.nb = nb ;
}
public void run ()
{
try
{
for(int i=0 ; i<nb ; i++)
{
fen.AddText ("test "+i+"\n");
sleep (500);
}
}
catch (InterruptedException e) {}
}
}
public class MaFenetre
{
public static void main (String args[])
{
Fenetre fen = new Fenetre() ;
fen.setVisible(true) ;
MyThread test = new MyThread (15) ;
test.setFenetre(fen);
test.start() ;
}
}