申し訳ありませんが、スレッドを使用するのは初めてです。Java Swing GUI - スレッドを常時スリープ状態にして、クリックで目を覚ます方法は?
私は、Parlamiクラスのスレッドをスリープ状態にして、actionListenerでのみ起動できるようにします。
私はこの方法を試みましたが、機能していない、彼はまだ眠っています。 スレッドをこの方法で使用するのは正しいですか、wait()を使用する必要がありますか?
package parlami;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author giacomofava
*/
public class Parlami
{
public boolean finito = false;
public String s="";
public void ascolta()
{
int i=0;
while (i<=1500)
{
// dormi 50 millisecondi
try
{
Thread.sleep(50);
i+=40;
}
catch (InterruptedException e)
{
}
while (voce.SpeechInterface.getRecognizerQueueSize() > 0)
{
s = s+"\n"+voce.SpeechInterface.popRecognizedString();
}
}
}
public String scrivi()
{
return "Hai detto: "+s;
}
public void leggi()
{
voce.SpeechInterface.synthesize(s);
}
public void dormi(int milli)
{
try
{
System.out.println("i'm sleeping");
Thread.sleep(milli);
}
catch (InterruptedException ex)
{
System.out.println("i'm awake ");
ascolta();
}
}
}
これはGUIです:あなたはスイングイベントスレッド上Thread.sleep
を呼び出した場合、あなたは役に立たない、それをレンダリングするスリープ状態にアプリケーション全体を配置します
public class GUI extends JFrame
{
private Parlami p;
private JPanel nord, centro;
private JButton registra, leggi;
private JTextArea display;
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
p=new Parlami();
initComponents();
}
private void initComponents()
{
voce.SpeechInterface.init("./lib", true, true,"./lib/gram", "vocabolario");
// N O R D
nord=new JPanel();
display=new JTextArea("");
display.setForeground(Color.GREEN);
display.setBackground(Color.BLACK);
nord.setBackground(Color.BLACK);
nord.add(display);
// C E N T R O
centro=new JPanel();
registra=new JButton("tieni premuto per registrare");
registra.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
Thread.currentThread().interrupt();// <-------- HERE I TRY TO AWAKE HIM
display.setText(p.scrivi());
}
});
centro.add(registra);
leggi=new JButton("leggi");
centro.add(leggi);
this.setLayout(new BorderLayout());
this.add(nord, BorderLayout.NORTH);
this.add(centro, BorderLayout.CENTER);
this.setSize(700,300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
p.dormi(50000); // <-------- HERE I TELL HIM TO SLEEP
}
}
代わりo'Thread.currentThread(に適している))、(中断; '、していますあなたはp.interrupt()を試しましたか? 'Parlami'は別個のスレッドでなければなりません(つまり、Runnableを実装することによって)。また、私はそれがとにかく40msだけ眠っていることに気付きます。私は待機/通知を使用します。 –
「ロック」については、「オブジェクトのロック」(https://docs.oracle.com/javase/tutorial/essential/concurrency/newlocks.html)から始めることをお勧めします。アイデアは " 1つのスレッドのロックで「待機」し、ロックの同じインスタンスを使用して、「通知する」は、処理しなければならない更新が発生したことを監視します。スイングはシングルスレッドであることを覚えておいてください。(ロックオブジェクトを待つような)EDT上でアクションを実行しないでください。EDT内からUIを更新するだけです。 – MadProgrammer
はい、私はすでにparlami.interruptで試しています。 ():( –