0
我試圖做的是一個Appled,它引發2個線程,每個線程運行一個通過無限循環增加自身的計數器 然後我在Applet的paint()方法中使用while(true),該方法不斷繪製計數器,問題是我也有2個按鈕,每個按鈕用於停止每個線程,但paint()方法中的無限循環不會讓我沒有點擊沒有人,也沒有關閉該小程序的窗口,也沒有什麼Applet中的paint()方法中的無限循環不允許我與顯示的按鈕進行交互
下面的截圖,然後代碼
順便說一句我敢肯定這個問題是塗料()循環,如果我禁用LO我可以與按鈕進行交互,但計數器顯然沒有更新,奇怪的是,我將鼠標光標放在按鈕上以顯示它的形式,例如當您想調整窗口的大小,但沒有捕獲的時候它:/
http://i.imgur.com/PJnDI4u.png
公共類MainApplet擴展小程序實現的ActionListener {
private static final long serialVersionUID = -2500043816999861110L;
private Font fuente;
private Button bUno, bDos;
private HiloContador hUno, hDos;
public void init() {
setBackground(Color.LIGHT_GRAY);
fuente = new Font("Verdana",Font.BOLD,26);
bUno = new Button("Parar");
bUno.addActionListener(this);
bDos = new Button("Parar");
bDos.addActionListener(this);
bUno.setSize(40,20);
add(bUno);
bDos.setSize(40,20);
add(bDos);
hUno = new HiloContador(20);
hUno.start();
hDos = new HiloContador(40);
hDos.start();
}
@SuppressWarnings({ "deprecation", "static-access" })
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(bUno)){
hUno.parar();
bUno.setLabel("1 parado");
}else if (e.getSource().equals(bDos)){
hDos.parar();
bDos.setLabel("2 parado");
}
}
public void paint(Graphics g) {
while (true){
g.clearRect(1,1,getSize().width,getSize().height); //dibuja la ventana
g.setFont(fuente);
g.drawString(hUno.getContador()+"",40,60);
g.drawString(hDos.getContador()+"",100,60);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
'paint()'方法不應該有一個循環。相反,嘗試在線程中運行更新。代碼示例[here](http://www.java-examples.com/create-number-counter-applet-using-thread-example)和更多解釋的示例[here](http://www.dmc.fmph .uniba.sk /的public_html/DOC /的Java/ch10.htm)。 – cxw
如果你放置了一個永不結束的循環,那麼你會阻塞事件分派線程(這是處理鼠標事件的線程)。 PS:看看https://docs.oracle.com/javase/7/docs/api/java/awt/EventQueue.html – Warrior
不要阻塞EDT(Event Dispatch Thread)。發生這種情況時,GUI將「凍結」。有關詳細信息和修補程序,請參見[Swing中的併發](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 –