Em mới học Swing. Em có viết một đoạn code có chức năng như đồng hồ bấm giờ. Nhưng khi bấm vào Button để lấy thời gian và setText vào JLabel thì có lỗi. Em nghi là do luồng nhưng chưa có hướng xử lí. Các bác xem hộ em với. Em cảm ơn nhiều:
class Demo4 implements ActionListener{
JLabel lbStatus;
clocktime1 cl;
JLabel lbCut;
JButton btn;
JFrame jfm;
Demo4(){
jfm= new JFrame("Hello");
lbStatus= new JLabel("00000000");
btn= new JButton("Cut");
lbCut=new JLabel("00:00:00");
jfm.setLayout(new FlowLayout());
jfm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jfm.add(btn);
btn.addActionListener(this);
jfm.add(lbStatus);
jfm.add(lbCut);
jfm.setSize(200,300);
jfm.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Cut")){
// jfm.add(lbCut=new JLabel(cl.str));
lbCut.setText(cl.str);
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
class clocktime1{
Demo4 dm4= new Demo4();
int ms=0;
int s=0;
int m=0;
String str="";
clocktime1(){
// RunTime run1= new RunTime();
try{
for(;;){
Thread.sleep(1);
ms++;
if(ms==1000){
s++;
ms=0;
}
if(s==60){
m++;
s=0;
}
dm4.lbStatus.setText(m+":"+s+":"+ms);
str=m+":"+s+":"+ms;
// run1.lbStatus.setText(m+":"+s+":"+ms);
// System.out.println(m+":"+s+":"+ms);
}
}catch(Exception er){
System.out.println("Error Runtime:"+er);
}
}
}
public class NewClass {
public static void main(String[] args) {
clocktime1 cl= new clocktime1();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Demo4 dm= new Demo4();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
}


83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?