Em viết 1 đoạn code nhỏ như bên dưới. Ace nào có thể giải thích hộ em tại sao khi em (run) rồi nhập vào 1 chuỗi tại sao chữ nó lại k nhấp nháy, trong khi em debug nó lại nhấp nháy (Em cảm ơn nhiều ạ~).
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends JFrame{
private static JLabel label;
private static JPanel panel;
private static String s = "";
public Test(){
System.out.println("Moi ban nhap vao ten cua minh: ");
s = new Scanner(System.in).nextLine();
this.setVisible(true);
this.setSize(new Dimension(300, 300));
panel = new JPanel();
label = new JLabel(s);
panel.add(label);
this.add(panel);
}
public static void main(String arg[]){
Runnable run = ()->{
Test test = new Test();
for(;;){
label.setText("");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
label.setText(s);
}
};
Thread thread = new Thread(run);
thread.run();
}
}
kiểu như mượn tay giết người ấy
trong swing thì có class SwingUtilities với 2 phương thức invokeLater(bất đồng bộ, nghĩa là nó giao việc cho thèn main thread rồi thì không care nữa) và invokeAndWait(đồng bộ, nghĩa là nó đợi cho main thread làm xong việc mà nó giao rồi mới chạy tiếp).
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?